A list is a sequence of elements. They’re called arrays in every other programming language on the planet, but since Python is special and demanding we’ll call them lists.

Creating a list

Making a list is simple - just put square brackets around a list of things, separating each element with a comma.

a_cool_list = [1, 2, 3, 4, 5]

Using a list

When you want an element, you use brackets to grab a specific one. The weird thing is the first element is 0, not 1.

This number is called an index.

presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe"]

# Use [0] to get the FIRST one
presidents[0] # Washington

# Use [2] to get the THIRD one
presidents[2] # Jefferson

# You can use negative numbers to work your way from the end of the list
presidents[-1] # Monroe

Looping through a list

Sometimes you want to do something to every item in a list.

The wrong way

If you love typing, you might think to do something like this

presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe"]

# Print out each president's name
# (Don't ever do this.)
president = presidents[0]
president = presidents[1]
president = presidents[2]
president = presidents[3]
president = presidents[4]

But no! We’re programmers, we’re lazy. It would be terribly if we had more than 5 presidents.

The right way

To accomplish this the simple way you use something called a for loop.

presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe"]

# Print out each president's name
for president in presidents:

Simpler, right?

The indented part is executed for every element of the list, in order. So first it will print Washington, then Adams, then Jefferson, etc. You can put as much stuff as you want inside of the loop as long as it’s indented - math, if statements, anything you want.

But where did president come from? How does Python know it’s the singular of presidents? It doesn’t, we made it up! You can name that variable anything.

presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe"]

# Use a dumb variable name
for buttered_popcorn in presidents:

You’ll use for loops all of the time. When something is going wrong with them, make sure your indenting is correct!

Functions and methods

To read about functions and methods that are useful for lists, scroll down on the functions and methods page.