← All posts

aiJul 2, 20251 min read

Python Built-in Container Types

Python includes ten core container types organised into three categories: sequences, sets, and mappings. Each container holds references to other objects and supports membership tests (in).

Sequences (7 Types)

Sequences are ordered and indexable collections. Some are mutable; others are not.

1. list

  • Mutable, ordered collection of arbitrary objects
  • Allows duplicates
  • Syntax: fruits = ['apple', 'banana', 'cherry']

2. tuple

  • Immutable, ordered collection
  • Allows duplicates
  • Syntax: coords = (10, 20, 30)

3. range

  • Immutable sequence of integers
  • Defined by start, stop, step
  • Efficient for loops, no full list in memory
  • Syntax: for i in range (1, 5): # 1, 2, 3, 4

4. str

  • Immutable sequence of Unicode characters
  • Supports slicing, concatenation
  • Syntax: greeting = "Hello, World!"

5. bytes

  • Immutable sequence of bytes (0–255)
  • Use for binary data
  • Syntax: data = b’\x01\x02\x03′

6. bytearray

  • Mutable counterpart to bytes
  • Supports in-place modification
  • Syntax: buf = bytearray(b’\x00\x01′)

buf[0] = 0xFF

7. memoryview

  • View on buffer-supporting objects (bytes, bytearray)
  • Allows slicing without copying
  • Syntax: mv = memoryview(b’abcdef’)

slice_mv = mv[2:4] # b’cd’

Sets (2 Types)

Sets store unordered, unique elements. Fast membership and set operations.

8. set

  • Mutable collection of unique, hashable objects
  • Syntax: primes = {2, 3, 5, 7}

primes.add(11)

9. frozenset

  • Immutable version of set
  • Can be used as dictionary keys or elements of another set
  • Syntax: frozen = frozenset([1, 2, 2, 3]) # {1, 2, 3}

Mappings (1 Type)

Mappings associate keys with values.

10. dict

  • Mutable collection of key→value pairs
  • Keys must be hashable and unique
  • Supports iteration over keys, values, items
  • Syntax: person = {‘name’: ‘Alice’, ‘age’: 30}

person['city'] = ‘Tokyo’

Each of these containers has its performance characteristics and use cases. It can be mutable or immutable types.

Comment

Comments

Be the first to comment

Your email is never shown. Comments appear after a quick check.