Lists are mutable ([1, 2]
), tuples are immutable ((1, 2)
).
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(key, value)
zeros = [0] * 5 # [0, 0, 0, 0, 0]
copy1 = original[:] # Slice
copy2 = original.copy() # Method
copy3 = list(original) # Constructor
⚠️ Avoid using copy = original
— it creates a reference, not a new list.
unique = list(set(my_list))
Note: This does not preserve order.
A concise way to create lists:
squares = [x*x for x in range(10)]
Yes. Tuples can hold lists or dictionaries:
t = ([1, 2], [3, 4])
t[0][0] = 100 # Allowed
t = (42,) # The comma is required
a, b, c = (1, 2, 3)
value = my_dict.get("key", "default_value")
for key, value in my_dict.items():
print(key, value)
Keys must be immutable types like strings, numbers, or tuples. Lists and dicts can’t be keys.
del my_dict["key"]
removed = my_dict.pop("key", "default")