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
| Operation | list | dict |
|---|---|---|
| Index / lookup | O(1) | O(1) average |
| Append | O(1) amortised | O(1) average |
| Search by value | O(n) | O(n) |
| Insert at front | O(n) | n/a |
Loading Comments...