ITERATING THROUGH A LIST

We’ve learned how to display the elements of a list. The problem is that we haven’t been able to display all the elements on their own easily. We have either had to display only one element using the list index or display the list as a whole. In this section, you will learn how to iterate through a list.

Let’s start off by using the method you will most likely recognize the most, by using the index of the element.

Sample Code

In this first example, we will iterate through a list using the index value of the element.

[python]
#Create the list
word = [‘M’, ‘e’, ‘r’, ‘i’, ‘v’, ‘a’, ‘l’, ‘e’]

#Looking at this list, we know there are 8 elements that have the index from 0 – 7
#This works very well with the range() method.
#We can use this fact to get each individual element to print on a new line using the ‘for’ loop

for i in range(8): #index 0 to 7
print(word[i]) #i will take on a new value each time and print that element
[/python]

Copy the code above and run it in the interpreter below.

Using the ‘in’ Keyword

Instead of using the index of the element, we can just use the element itself. What the program can do is have Python iterate to the next element if there is another element in the list. In other words, for each element IN the list, do something.

We can also use ‘in’ to see if a certain element is actually in the list at all. Have a look at the code below.

[python]
#Create a Grocery List
groceries = [‘loaf of bread’, ‘container of milk’, ‘stick of butter’, ‘granola bars’, ‘ice cream’]

#Print the List
for element in groceries:
print(element)
#In this situation, element will take on the value of an item in the list, print it, move to the next one and repeat.
[/python]

As stated before, we can use the keyword ‘in’ to see if a certain element is in a list. Let’s expand on our last program.

[python]
#Create a Grocery List
groceries = [‘loaf of bread’, ‘container of milk’, ‘stick of butter’, ‘granola bars’, ‘ice cream’]

#Print the List
for element in groceries:
print(element)

if ‘ice cream’ in groceries:
print("I love ice cream!")
[/python]

Sample Code

Copy the code above and execute it. Does it create the result you expected? Change the items in the list to see the different results. Try creating your own list and printing each of its items. Try using different if statements and adding elif or else statements to expand on the program.

Check Your Understanding

Before moving to the next section, let’s see how well you know the current material.

  1. Create a program that will display each of the elements of a list on the same line.
  2. Create a program that will allow a user to search if a letter is in a given string.
  3. Create a program that has list list with 5 integers. Allow the user to enter a number and then multiply each of the integers by that number.

Once you are done, compare your programs to the ones show in the sample solution.