Data Types [01]: Python Built-In Types

3 minute read

Published:

The principal built-in types in Python are numerics, sequences, mappings, classes, instances and exceptions. Reference [this] site for a complete description. This post will cover some of the commonly used python built-in types.


Numeric Types

  • int
  • float
  • complex

Supported Operations

  • x + y, x - y, x * y, x / y, x // y, x % y
  • x| y, x ^ y, x & y, x << n, x >> n, `~x’
  • abs(x), int(x), float(x)
  • complex(re,im), c.conjugate()
  • divmod(x, y), pow(x, y), x ** y
  • math.trunc(x), round(x[, n]), math.floor(x), math.ceil(x)

Sequence Types

  • list
    • Using a pair of square brackets to denote the empty list: []
    • Using square brackets, separating items with commas: [a], [a, b, c]
    • Using a list comprehension: [x for x in iterable]
    • Using the type constructor: list() or list(iterable)
    • Mutable
  • tuple
    • Using a pair of parentheses to denote the empty tuple: ()
    • Using a trailing comma for a singleton tuple: a, or (a,)
    • Separating items with commas: a, b, c or (a, b, c)
    • Using the tuple() built-in: tuple() or tuple(iterable)
    • Immutable
  • range
    • range(stop)
    • range(start, stop[, step])
    • Immutable
  • str
    • Single quotes: 'allows embedded "double" quotes'
    • Double quotes: "allows embedded 'single' quotes"
    • Triple quoted: '''Three single quotes''', """Three double quotes"""
    • Immutable

Common Operations

  • x in s, x not in s
  • s + t, s * n
  • s[i], s[i:j], s[i:j:k]
  • len(s), min(s), max(s)
  • s.index(x[, i[, j]]), s.count(x)

Mutable Sequence Operations

  • s[i] = x, s[i:j] = t, s[i:j:k] = t
  • del s[i], del s[i:j], del s[i:j:k], s.clear()/del s[:]
  • s.append(x), s.pop()/s.pop(i), s.remove(x)
  • s.copy()/s[:], s.reverse()
  • s.extend(t)/s += t, s *= n, s.insert(i, x)

Mapping Types

  • dict
    • Use a comma-separated list of key: value pairs within braces: {'jack': 4098, 'sjoerd': 4127}
    • Use a dict comprehension: {}, {x: x ** 2 for x in range(10)}
    • Use the type constructor: dict(), dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200)
    • Mutable
      • Use keys to change a dict instead of index like that in a list

Dict Operations

  • list(d), len(d), d[key]
  • d[key] = value, del d[key], clear()
  • key in d, key not in d
  • get(key[, default])
  • d.copy(), reversed(d)
  • d.pop(key[, default]), d.popitem()

Set Types

  • set
    • Use a comma-separated list of elements within braces: {'jack', 'sjoerd'}
    • Use a set comprehension: {c for c in 'abracadabra' if c not in 'abc'}
    • Use the type constructor: set(), set('foobar'), set(['a', 'b', 'foo'])
    • Immutable (except add() and remove())

Binary Types

  • bytes
    • Single quotes: b'still allows embedded "double" quotes'
    • Double quotes: b"still allows embedded 'single' quotes"
    • Triple quoted: b'''3 single quotes''', b"""3 double quotes"""
    • Immutable
  • bytearray
    • Creating an empty instance: bytearray()
    • Creating a zero-filled instance with a given length: bytearray(10)
    • From an iterable of integers: bytearray(range(20))
    • Copying existing binary data via the buffer protocol: bytearray(b'Hi!')
    • Mutable

Iterator Types

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration.

Lists, tuples, dictionaries, str and sets are all iterable objects.

Dict Operations

  • iterator = iter(iterableObj)
  • next(iterator)
animals = {'dog', 'cat', 'pig', 'goat'}
iterator = iter(animals)

next(iterator)
Out[104]: 'cat'

next(iterator)
Out[105]: 'goat'

next(iterator)
Out[106]: 'pig'

next(iterator)
Out[107]: 'dog'

To create an object/class as an iterator we have to implement the methods iter() and next() to the object.

iterator.__iter__(): Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.

iterator.__next__(): Return the next item from the iterator. If there are no further items, raise the StopIteration exception.


Comments