Skip to main content
Foundation

Lists and Dictionaries

Lists​

Ordered, mutable collections.

lists.py
nums = [3, 1, 2]
nums.append(4) # [3, 1, 2, 4]
nums.sort() # [1, 2, 3, 4]
print(nums[0], nums[-1], nums[1:3]) # 1 4 [2, 3]

List comprehension​

comprehension.py
squares = [n * n for n in range(5) if n % 2 == 0]  # [0, 4, 16]

Dictionaries​

Key-value mappings (insertion ordered since Python 3.7).

dicts.py
user = {"name": "Asha", "age": 21}
user["city"] = "Pune"
print(user.get("email", "n/a")) # n/a

for key, value in user.items():
print(key, value)

Dictionary comprehension​

dict_comprehension.py
lengths = {w: len(w) for w in ["code", "prep"]}

Time complexity cheat sheet​

Operationlistdict
Index / lookupO(1)O(1) average
AppendO(1) amortisedO(1) average
Search by valueO(n)O(n)
Insert at frontO(n)n/a
Loading Comments...