Skip to content
Laviyx Learn

Try

Python Data Structures Cheat Sheet

Lists, tuples, sets, and dictionaries with their most useful methods.

Updated

# → value shows what an expression returns. # name → value shows what a variable holds after that line.

Which one should I use?#

TypeSyntaxOrderedChangeableDuplicatesBest for
list[1, 2, 3]yesyesyescollections that grow, shrink or get sorted
tuple(1, 2, 3)yesnoyesfixed records, multiple return values, dict keys
set{1, 2, 3}noyesnounique values, fast in checks
dict{"a": 1}yes (insertion)yesunique keyslooking things up by key

Lists#

Python
nums = [3, 1, 2]
nums[0]                 # → 3
nums[-1]                # → 2
nums[0:2]               # → [3, 1]
len(nums)               # → 3

nums.append(4)          # nums → [3, 1, 2, 4]
nums.insert(0, 9)       # nums → [9, 3, 1, 2, 4]
nums.extend([5, 6])     # nums → [9, 3, 1, 2, 4, 5, 6]
nums.remove(9)          # nums → [3, 1, 2, 4, 5, 6]
nums.pop()              # → 6
nums.pop(0)             # → 3
nums                    # → [1, 2, 4, 5]

nums.index(4)           # → 2
nums.count(2)           # → 1
4 in nums               # → True

nums.reverse()          # nums → [5, 4, 2, 1]
nums.sort()             # nums → [1, 2, 4, 5]
sorted(nums, reverse=True)   # → [5, 4, 2, 1]
min(nums), max(nums), sum(nums)   # → (1, 5, 12)

sort() and reverse() change the list and return None; sorted() returns a new list. Copy with nums.copy() or nums[:], never b = a.

Slicing#

Python
s = [10, 20, 30, 40, 50]
s[1:4]                  # → [20, 30, 40]
s[:2]                   # → [10, 20]
s[2:]                   # → [30, 40, 50]
s[::2]                  # → [10, 30, 50]
s[::-1]                 # → [50, 40, 30, 20, 10]

[start:stop:step]: stop is excluded. Works on lists, tuples and strings.

Tuples#

Python
point = (3, 4)
point[0]                # → 3
x, y = point            # x → 3
single = (5,)           # the comma makes a tuple
first, *rest = (1, 2, 3, 4)   # rest → [2, 3, 4]
(1, 2, 1).count(1)      # → 2

Tuples cannot be changed. Use them as dictionary keys: {("Mumbai", "Pune"): 150}.

Sets#

Python
tags = {"python", "sql"}
tags.add("web")
tags.discard("java")    # no error if missing (remove() raises KeyError)
"sql" in tags           # → True
len(tags)               # → 3

a = {1, 2, 3}
b = {2, 3, 4}
a | b                   # → {1, 2, 3, 4}
a & b                   # → {2, 3}
a - b                   # → {1}
a ^ b                   # → {1, 4}
{1, 2} <= a             # → True

sorted(set([3, 1, 3, 2]))       # → [1, 2, 3]
list(dict.fromkeys([3, 1, 3, 2]))   # → [3, 1, 2]

Empty set: set(), because {} is an empty dict. Sets have no order and no indexes.

Dictionaries#

Python
user = {"name": "Asha", "age": 21}
user["name"]            # → 'Asha'
user.get("email")       # → None
user.get("email", "-")  # → '-'
"age" in user           # → True

user["age"] = 22        # update
user["city"] = "Pune"   # add
user.pop("city")        # → 'Pune'
user                    # → {'name': 'Asha', 'age': 22}

list(user.keys())       # → ['name', 'age']
list(user.values())     # → ['Asha', 22]
list(user.items())      # → [('name', 'Asha'), ('age', 22)]

merged = {"a": 1} | {"b": 2}   # merged → {'a': 1, 'b': 2}
user.setdefault("tags", [])    # → []
Python
for key, value in user.items():
    print(key, value)

Counting and grouping#

Python
from collections import Counter, defaultdict

words = "the cat and the hat".split()

counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1   # counts["the"] → 2

Counter(words).most_common(1)   # → [('the', 2)]

groups = defaultdict(list)
for w in ["apple", "avocado", "banana"]:
    groups[w[0]].append(w)
dict(groups)            # → {'a': ['apple', 'avocado'], 'b': ['banana']}

Comprehensions#

Python
[n * n for n in range(5)]           # → [0, 1, 4, 9, 16]
[n for n in range(10) if n % 3 == 0]   # → [0, 3, 6, 9]
[n if n > 0 else 0 for n in [-1, 2]]   # → [0, 2]
{n: n * n for n in range(3)}        # → {0: 0, 1: 1, 2: 4}
{len(w) for w in ["a", "bb", "cc"]}   # → {1, 2}
sum(n * n for n in range(4))        # → 14

Looping helpers#

Python
names = ["Asha", "Ravi"]
scores = [92, 85]

list(enumerate(names, start=1))     # → [(1, 'Asha'), (2, 'Ravi')]
list(zip(names, scores))            # → [('Asha', 92), ('Ravi', 85)]
dict(zip(names, scores))            # → {'Asha': 92, 'Ravi': 85}
sorted(zip(names, scores), key=lambda p: p[1])   # → [('Ravi', 85), ('Asha', 92)]

Common gotchas#

GotchaFix
b = a shares one listb = a.copy() (or copy.deepcopy for nested data)
nums = nums.sort() sets nums to Nonecall nums.sort() alone, or use sorted()
{} is an empty dictuse set() for an empty set
d["missing"] raises KeyErrord.get("missing", default)
Lists can't be dict keys or set membersuse tuples
Changing a list while looping over itloop over a copy, or build a new list

Full lessons: Lists, Tuples, Sets, Dictionaries, Comprehensions.

Want the full explanations? Go to the Learn Python course →