Lists in Python

Some Examples

Click the blue "This Gist" link at the bottom left of each example to see the source code on my Github account.

First, just create a short list and print it out. Make sure your code looks exactly like mine!

Lists store items in order, and you can look up any item in the list according to its position, or "index".

It's fine to mix different types in the same list, if that's what you want! Python is a relaxed language.

Next, let's make a list of the colors that we can use to draw in turtle, then use each color as we draw a square. I set the speed to 1 so it's easier to see the for loop happening.

The other neat thing to do with lists is look at a chunk of items that are right next to each other. The syntax is very similar to indexing, but it accesses multiple items in the list. This is called "slicing".

Now let's take a look at Python's built-in method "range". This is one of my favorite list shortcuts. In Python 2.7, using the "range" method will return a list of all the integers between 0 and 1 less than the parameter.In Python 3, you need to change the type of range to list() to see a list. If you are just iterating over the values, you only need "range". In this small example, "range" gives us access to [0, 1, 2, 3, 4]. There are 4 elements total, from 0 to 4.

What do you think these lists will contain? Print them out and see!

Copying a list isn't as simple as you might think. Try to guess what this code will print before you run it.

Lastly, let's take a look at some of the methods that we can call on lists. Follow along, and pay extra attention to which of these methods change your list, and which only access it.

That's all for now!