Python lists cheat sheet 📋
Adding, removing, sorting, slicing and looping over lists, plus list comprehensions. Every snippet runs in your browser, and the page prints on one sheet.
Make and read
nums = [5, 3, 8, 1]
print(nums[0], nums[-1])
print(nums[1:3])
print(len(nums), sum(nums), max(nums), min(nums))Lists keep their order and can hold anything.
Add items
pets = ["cat"]
pets.append("dog")
pets.insert(0, "fish")
pets.extend(["hamster", "rabbit"])
print(pets)append adds one item to the end, extend adds several.
Remove items
pets = ["fish", "cat", "dog", "cat"]
pets.remove("cat")
last = pets.pop()
print(pets, last)
del pets[0]
print(pets)remove deletes the first match. pop takes the last item and gives it back.
Sort
scores = [42, 7, 19, 88]
print(sorted(scores))
print(sorted(scores, reverse=True))
scores.sort()
print(scores)
words = ["kiwi", "fig", "banana"]
print(sorted(words, key=len))sorted() returns a new list. .sort() changes the list and returns None.
Find things
nums = [4, 9, 4, 2]
print(9 in nums)
print(nums.index(4))
print(nums.count(4))index() raises ValueError when the item is missing, so check with in first.
Loop
colours = ["red", "green", "blue"]
for c in colours:
print(c)
for i, c in enumerate(colours, 1):
print(i, c)enumerate gives you the position and the item together.
List comprehensions
nums = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in nums]
evens = [n for n in nums if n % 2 == 0]
print(squares)
print(evens)[expression for item in list if condition] builds a new list in one line.
Copy safely
a = [1, 2, 3]
b = a
c = a.copy()
a.append(4)
print(b)
print(c)b = a gives two names for one list. Use .copy() for a separate list.