my_list = ["hello", "how are you", "goodbye"]my_list[1] = "hello" # modify by indexmy_list[-1] = "see you later" # modify last elementmy_list[2:] = ["see you", "bye"] # replace from index 2 to the endmy_list[:2] = ["greetings", "good morning"] # replace from start to index 2
Warning
Lists are mutable, but reassigning a list to a new variable does not copy it. Both names point to the same list in memory:
a = [1, 2, 3]b = ab.append(4)print(a) # [1, 2, 3, 4] (a is also modified)
Use b = a.copy() or b = a[:] to create a real copy.
Adding elements
my_list = ["a", "b"]my_list.append("c") # add to the end: ["a", "b", "c"]my_list.insert(1, "x") # insert at index 1: ["a", "x", "b", "c"]my_list.extend(["d", "e"]) # add multiple: ["a", "x", "b", "c", "d", "e"]my_list2 = my_list + ["f", "g"] # concatenation (creates new list)
Removing elements
my_list = ["a", "b", "c", "d"]my_list.pop() # removes and returns "d"my_list.pop(1) # removes and returns "b"my_list.remove("a") # removes first occurrence of "a"my_list.clear() # removes all elements
numbers = [3, 1, 4, 1, 5, 9]numbers.sort() # sorts in place (ascending)numbers.sort(reverse=True) # sorts in place (descending)sorted(numbers) # returns a new sorted list (original unchanged)
my_tuple = ("one", "two", "three")one, two, three = my_tuple # one = "one", two = "two", three = "three"# Ignore values with _a, _, c = (1, 2, 3) # a = 1, c = 3
Conversion
list(my_tuple) # converts tuple to listtuple(my_list) # converts list to tuple
Tip
Tuples are faster than lists and use less memory. Use them when the data should not change.
Dictionaries
Dictionaries are mutable collections of key-value pairs. They do not work by index, but by key.
my_dict = {"key1": "value1", "key2": "value2"}
Accessing values
my_dict["key1"] # "value1"my_dict.get("key1") # "value1" (same as [])my_dict.get("key3", "default") # "default" (returns default if key doesn't exist)
Warning
Accessing a non-existent key with [] raises a KeyError. Use .get() for safe access.
Modifying
my_dict["key1"] = "new value1" # modify existing keymy_dict["key3"] = "value3" # add new keymy_dict.update({"key4": "value4"}) # add/update multiple keys
Removing
del my_dict["key2"] # remove by keymy_dict.pop("key1") # remove and return valuemy_dict.popitem() # remove and return last inserted pairmy_dict.clear() # remove all elements
add() adds a single element, while update() adds all elements from an iterable.
Removing elements
my_set = {1, 2, 3, 4}my_set.remove(2) # removes 2my_set.discard(3) # removes 3 if it existsmy_set.pop() # removes and returns an arbitrary elementmy_set.clear() # removes all elements
Warning
remove() raises a KeyError if the element does not exist. discard() does nothing in that case.
Searching
my_set = {"a", "b", "c"}"a" in my_set # True"x" in my_set # False"a" not in my_set # False
Membership checks are generally very fast because sets are implemented using a hash table.
Set operations
Sets are especially useful for mathematical set operations.
Union
Returns all elements from both sets, removing duplicates.
Because a frozenset is immutable and hashable, it can be used as a dictionary key or as an element of another set.
groups = { frozenset({"admin", "user"}), frozenset({"guest"})}
Note
Normal set elements must be hashable, so you can store values such as numbers, strings and tuples, but not mutable values such as lists or dictionaries.