Lists and dictionaries are the two containers you'll use most in Python. A list keeps items in order. A dictionary stores values under names, called keys. These are the jobs people look up most often. Every example below was run, and the output shown under it is exactly what Python printed.
Lists
Add to a list
parts = ["resistor", "LED", "capacitor"]
parts.append("diode") # add one item to the end
print(parts)
parts.insert(1, "fuse") # add at position 1 (the second place)
print(parts)
parts.extend(["relay", "crystal"]) # add several items to the end
print(parts)
['resistor', 'LED', 'capacitor', 'diode']
['resistor', 'fuse', 'LED', 'capacitor', 'diode']
['resistor', 'fuse', 'LED', 'capacitor', 'diode', 'relay', 'crystal']
A common mistake is parts.append(["relay", "crystal"]), which adds the whole list as a single item. Use extend to add each item.
Remove from a list
parts.remove("fuse") # remove the first item equal to "fuse"
print(parts)
last = parts.pop() # remove and return the last item
print(last, parts)
first = parts.pop(0) # remove and return the item at position 0
print(first, parts)
del parts[1] # delete by position, returns nothing
print(parts)
['resistor', 'LED', 'capacitor', 'diode', 'relay', 'crystal']
crystal ['resistor', 'LED', 'capacitor', 'diode', 'relay']
resistor ['LED', 'capacitor', 'diode', 'relay']
['LED', 'diode', 'relay']
remove raises a ValueError if the item isn't there, and pop raises an IndexError on an empty list, so check first with if "fuse" in parts: if you're not sure.
Sort a list
values = [470, 10, 2200, 100]
values.sort() # sorts in place
print(values)
values.sort(reverse=True)
print(values)
names = ["led", "Diode", "capacitor"]
print(sorted(names)) # returns a new list
print(sorted(names, key=str.lower)) # ignore upper and lower case
print(names) # the original is unchanged
[10, 100, 470, 2200]
[2200, 470, 100, 10]
['Diode', 'capacitor', 'led']
['capacitor', 'Diode', 'led']
['led', 'Diode', 'capacitor']
list.sort() changes the list and returns None, so values = values.sort() is a bug: it leaves you with None. Use sorted() when you want a new list. Notice that plain sorting puts capital letters first; key=str.lower fixes that.
Reverse a list or a string
nums = [3, 1, 2]
nums.reverse()
print(nums)
word = "Ohm"
print(word[::-1]) # slice with a step of -1
print("".join(reversed(word)))
[2, 1, 3]
mhO
mhO
Strings can't be changed in place, so they have no reverse() method; slicing makes a new, reversed string.
Dictionaries
Add or change entries
pins = {"LED": 15, "button": 14}
pins["buzzer"] = 16 # add a new key
print(pins)
pins.update({"LED": 25, "relay": 17}) # change one, add another
print(pins)
{'LED': 15, 'button': 14, 'buzzer': 16}
{'LED': 25, 'button': 14, 'buzzer': 16, 'relay': 17}
Dictionaries keep the order you added keys in (guaranteed since Python 3.7). Each key appears only once, so assigning to an existing key replaces its value.
Get a value safely
print(pins.get("servo")) # None instead of an error
print(pins.get("servo", "not wired")) # or a default you choose
None
not wired
pins["servo"] would raise a KeyError, because there's no such key.
Remove an entry
removed = pins.pop("button")
print(removed, pins)
14 {'LED': 25, 'buzzer': 16, 'relay': 17}
Loop over keys and values
for name, pin in pins.items():
print(f"{name} is on GP{pin}")
LED is on GP25
buzzer is on GP16
relay is on GP17
Looping over the dictionary itself (for name in pins:) gives just the keys; .values() gives just the values.
Count things
counts = {}
for part in ["LED", "resistor", "LED"]:
counts[part] = counts.get(part, 0) + 1
print(counts)
{'LED': 2, 'resistor': 1}
Sort a dictionary by value
print(sorted(pins.items(), key=lambda kv: kv[1]))
[('buzzer', 16), ('relay', 17), ('LED', 25)]
Comments, while we're here
Python comments start with # and run to the end of the line. There's no block comment: to comment out several lines, put # in front of each one. Most editors do that for you with Ctrl+/ (Cmd+/ on a Mac). A triple-quoted string isn't a comment; it's a string that Python creates and throws away, and at the top of a function it becomes the function's docstring.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.