Intro to Computer Science

Python Cheat Sheet

Lists

Hold a bunch of related values in one variable.

Make one and look inside

Counting starts at 0, so the first item is at index 0.

Create a list

Square brackets, values separated by commas.

names = ["Steve", "Becca", "Alex"]
print(names)
Output
['Steve', 'Becca', 'Alex']

Get one item

The index goes in square brackets.

names = ["Steve", "Becca", "Alex"]
print(names[0])
print(names[1])
Output
Steve
Becca

Get the last item

-1 is the last one, no matter how long the list is.

names = ["Steve", "Becca", "Alex"]
print(names[-1])
Output
Alex

Count the items

len() gives how many are in the list.

names = ["Steve", "Becca", "Alex"]
print(len(names))
Output
3

Add and change

Replace an item

Assign straight to the index.

names = ["Steve", "Becca", "Alex"]
names[1] = "Yara"
print(names)
Output
['Steve', 'Yara', 'Alex']

Add to the end

Use this one

append() is the one you will use most.

names = ["Steve", "Becca", "Alex"]
names.append("Yara")
print(names)
Output
['Steve', 'Becca', 'Alex', 'Yara']

Add at a position

Everything from that spot on shifts over.

names = ["Steve", "Becca", "Alex"]
names.insert(2, "Yara")
print(names)
Output
['Steve', 'Becca', 'Yara', 'Alex']

Take things out

Remove the last item

pop() with nothing inside takes the last one.

names = ["Steve", "Becca", "Alex"]
names.pop()
print(names)
Output
['Steve', 'Becca']

Remove by position

Give pop() an index to pick which one.

names = ["Steve", "Becca", "Alex"]
names.pop(0)
print(names)
Output
['Becca', 'Alex']

Remove by value

remove() takes the value itself, not the index.

names = ["Steve", "Becca", "Alex"]
names.remove("Becca")
print(names)
Output
['Steve', 'Alex']

Go through every item

Loop over a list

name holds a different item each time around.

names = ["Steve", "Becca", "Alex"]
for name in names:
    print(f"Hi, {name}!")
Output
Hi, Steve!
Hi, Becca!
Hi, Alex!

Check if something is in the list

in and not in give back True or False.

names = ["Steve", "Becca", "Alex"]
if "Becca" in names:
    print("Becca is here.")
if "Yara" not in names:
    print("Yara is not here.")
Output
Becca is here.
Yara is not here.