Lesson 05-02: Looping over Lists

Learning Target: I can use a for loop to iterate over every element in a list.
Learning Target: I can use a for-each loop to iterate over every element in a list.

Looping by Referencing Index

We know that we can use a for loop to iterate through a list of numbers. This lets us iterate through every position in a list:

 
1
a = ['hi','hey','hello','howdy','holla']
2
for i in range(len(a)):
3
    print(a[i])
4
hi
hey
hello
howdy
holla

(ex_0502_1)

However, in python, there’s a much easier way!

Using a for-each loop

We can use a for each loop to do the same thing as above:

4
 
1
a = ['hi','hey','hello','howdy','holla']
2
for item in a:
3
    print(item)
4
hi
hey
hello
howdy
holla

(ex_502_2)

In our first example with i, i represented the index of each element of a. However, in this example, item represents the element itself! This is called a for-each loop because it runs a loop for each element in a list.

In case you’re wondering why this is, recall that range() is a function that generates a LIST of numbers! All you’re doing is iterating through that list! So really, every for loop in python is a for-each loop!

Checks for Understanding

Q#1

INSTRUCTIONS: Write a for loop below so it will print out every element in the list names.

4
 
1
names = ['Bobert','Danny','Pat','Chris','Snacks']
2
3
#write code below
4

(cfu_0502_1)

Q#2

INSTRUCTIONS: Given a list of integers numbers, return the sum of the elements in numbers.

4
 
1
def sumList(numbers):
2
    #write here
3
4

(cfu_0502_2)

Q#3

INSTRUCTIONS: Given a list of letters letters, return the count of vowels in the list.

4
 
1
def sumVowels(letters):
2
    #write here
3
4

(cfu_0502_3)

Next Section - Lesson 05-03: Basic List Functions