Lesson 05-02: Looping over Lists¶
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:
a = ['hi','hey','hello','howdy','holla']
for i in range(len(a)):
print(a[i])
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:
a = ['hi','hey','hello','howdy','holla']
for item in a:
print(item)
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
.
names = ['Bobert','Danny','Pat','Chris','Snacks']
#write code below
(cfu_0502_1)
Q#2¶
INSTRUCTIONS: Given a list of integers numbers
, return the sum of the elements in numbers
.
def sumList(numbers):
#write here
(cfu_0502_2)
Q#3¶
INSTRUCTIONS: Given a list of letters letters
, return the count of vowels in the list.
def sumVowels(letters):
#write here
(cfu_0502_3)