Python Mini Lesson: Lists and For Loops

1. Overview

What is a list in Python?
Things we can do with lists.
What is a for loop?
Examples of loops.

2. Python: Lists

Lists allow us to store multiple values together, in order. It's almost like having a row of cardboard boxes taped together: you can put something in each box and the items will stay in order!

Lists need to be created before you can use them. Here's how to create an empty list:

list1 = []

Now we can append new elements to the list:

print list1

What if we want to get a particular value held in a list? First, we need to know the index of the list element that holds the value we want. The index is like the street number of an address; the number increments by one for each building down the street. In the same way, counting from 0 to the element you want to access will give you the index.

Let's look at an example:

list2 = [7,5,6,23,15]
index = 2
print list2[index]


What other cool things you can do with lists?

Let's get the length:

size = len(list2)
print size

The code to print the last element in any list is below. Why do we need the -1?

print list2[len(list2)-1]

We can also sort a list:

print list2

3. Python: For Loops

When do you use loops?
Have you ever had a situation where you have to do the same thing over and over again? Think about a jump rope. If you aren't into the fancy tricks you...

Instead of writing jump 5 times, a loop makes it possible to write it once and assign it a number for how many times you want it written.

Let's jump 100 times:

for i in range(100):
    print "jump"

What if you wanted to print out all the letters in the word Computer

for letter in "Computer":
    print 'Current letter: ', letter

We can also access numbers in a range. Lets print numbers 0-99

for i in range(100):
    print i

In this for loop we use range(). range() creates a set that can be looped through. When we write range(100) we are actually saying: [0,1,2,3,4,5,...,98,99]. In fact, this loop does exactly the same thing as the previous one:

list3 = range(100)
for num in list3:
    print num

What if you wanted to add 0 - 19 to a list:

list4 = []
for i in range(20):

To print a list, we can we can use:

print list4

Or we can use:

for i in range(len(list4)):
    print list4[i]

Loops can have multiple lines, too! Let's print some stars:

count = 16
for i in range(6):
    count = count - i
    print ('*' * count)

4. Python Lists and Loops: Practice Problems

  1. Starting with an empty list, make a list that contains the names of the planets of our solar system.
  2. Create a list using range(7). Using a loop, extend the list of integers up to and including the number 25.
  3. Create two lists that contain the letters of two different sentences, e.g., sentence1 = ['H', 'e', 'l', 'l', 'o', '.']. Using a loop, add the letters of the second sentence to the end of the first sentence.