Skip to content

Data Structures

Python ships four general-purpose container types in the language core — no imports required.

TypeSyntaxMutableOrderedDuplicates
list[1, 2, 3]yesyesyes
tuple(1, 2, 3)noyesyes
dict{"a": 1}yesyes (3.7+)keys: no
set{1, 2, 3}yesnono

Each type has a distinct strength: lists for ordered sequences, tuples for fixed records, dicts for key-value lookup, and sets for membership tests and set algebra.

  • Reach for a list when you need to append, sort, or index items by position.
  • Use a tuple when the data is fixed and positional meaning matters (e.g., an RGB colour, a database row).
  • Use a dict when you need fast key-based lookup or want to group named attributes without defining a class.
  • Use a set when uniqueness is the primary concern or you need union / intersection / difference operations.
from collections import namedtuple
# --- list ---
nums = [1, 2, 3, 4, 5]
print('list:', nums)
print('sum:', sum(nums))
# --- tuple unpacking ---
coords = (10, 20, 30)
x, y, z = coords
print('tuple unpack:', x, y, z)
# --- dict (insertion order preserved since Python 3.7) ---
scores = {'alice': 95, 'bob': 87, 'carol': 92}
print('dict:', scores)
print('alice score:', scores['alice'])
# --- set (duplicates removed automatically) ---
unique = {3, 1, 4, 1, 5, 9, 2, 6, 5}
print('set:', sorted(unique))
# --- namedtuple: lightweight named record ---
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print('namedtuple:', p.x, p.y)
Which built-in collection type does NOT allow duplicate values?
Since Python 3.7, which collection preserves insertion order?
Which collection is immutable?
Which type is best for fast membership testing of a large number of unique items?