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:
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:
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.
Q#2¶
INSTRUCTIONS: Given a list of integers numbers, return the sum of the elements in numbers.
Q#3¶
INSTRUCTIONS: Given a list of letters letters, return the count of vowels in the list.