for loops#In the previous section we introduced lists in Python, one form of a collection of values that can be represented by a single variable. In this lesson we will learn how to use loops. Loops allow parts of code to be repeated some number of times, such as iterating over all of the items in a Python list and performing a calculation on each item. Show
A (bad) example#Let’s consider an example using the list below: european_cities = ["Helsinki", "Paris", "Barcelona", "Uppsala"] Suppose we want to print out the name of each city in our list. We could use the index value for each city and do the following: But this is a bad idea. Why? Well there are two reasons. First, it does not scale nicely for long lists, and will take forever to type in. Second, it won’t work if the length of the list has fewer than 4 cities. Let’s see an example with a new list. european_cities = ["Riga", "Rome", "Athens"] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) /tmp/ipykernel_284065/1729903104.py in <module> ----> 1 european_cities[3] IndexError: list index out of range Introducing the for loop#We could do a much better job by using a european_cities = ["Amsterdam", "Brussels", "Lisbon", "Reykjavik"] for city in european_cities: print(city) Amsterdam Brussels Lisbon Reykjavik Not only is this shorter, but it is also more flexible. Try printing out a different list of cities such as us_cities = [ "Detroit", "Chicago", "Denver", "Boston", "Portland", "San Francisco", "Houston", "Orlando", ] for city in us_cities: print(city) Detroit Chicago Denver Boston Portland San Francisco Houston Orlando for loop format#For loops in Python have the general form below. for variable in collection: do things with variable Let’s break down the code above to see some essential aspect of
In summary, Your daily for loop#Figure 2.3. A cat’s daily routine as an example loop. Original comic from https://www.bugmartini.com/comic/cats-eye/. Like many other programming concepts, the idea of looping through actions is something that is already perhaps more familiar to you than you think. Consider your actions during a given day. Many people have certain routines they follow each day, such as waking up, taking a shower, eating breakfast and brushing their teeth. In Python code, we might represent such actions as follows: for day in my_life: wake_up() take_shower() eat_breakfast() brush_teeth() ... Note that for loop variables#Note that the variable used in a weather_conditions = [ "rain", "sleet", "snow", "freezing fog", "sunny", "cloudy", "ice pellets", ] for weather in weather_conditions: print(weather) rain sleet snow freezing fog sunny cloudy ice pellets What is its value of print("After the loop, weather is", weather) After the loop, weather is ice pellets For loops using the range function#A loop can be used to iterate over any list of values in Python. So far we have considered only lists, but we could also write a loop that
performs a calculation a specified number of times by using the for value in range(5): print(value) In this case, we use a special function called Help on class range in module builtins: class range(object) | range(stop) -> range object | range(start, stop[, step]) -> range object | | Return an object that produces a sequence of integers from start (inclusive) | to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. ... (output truncated) Question 2.4#The program below will print numbers to the screen using the
for i in range(...): print(i) Using the documentation that is produced when you run # You can use this cell to enter your solution.
# Solution for i in range(2, 9, 3): print(i) Looping over lists using index values#Since we already know how to find the length of a list using the for i in range(len(numbers)): print("Value of i:", i) print("Value of numbers[i] before addition:", numbers[i]) numbers[i] = numbers[i] + i print("Value of numbers[i] after addition:", numbers[i]) print("") Value of i: 0 Value of numbers[i] before addition: 5 Value of numbers[i] after addition: 5 Value of i: 1 Value of numbers[i] before addition: 6 Value of numbers[i] after addition: 7 Value of i: 2 Value of numbers[i] before addition: 7 Value of numbers[i] after addition: 9 Value of i: 3 Value of numbers[i] before addition: 8 Value of numbers[i] after addition: 11 There are several important things to observe in this
The variable Why use index value to loop over a list?#Good
question. First off, if you want to update individual values in a list you’re likely going to need to loop that includes the index values. There are functions such as cities = ["Helsinki", "Stockholm", "Oslo", "Reykjavik", "Copenhagen"] countries = ["Finland", "Sweden", "Norway", "Iceland", "Denmark"] As you can see we have 5 cities and 5 corresponding counties. Let’s print out each pair using a single for loop. for i in range(len(cities)): print(cities[i], "is the capital of", countries[i]) Helsinki is the capital of Finland Stockholm is the capital of Sweden Oslo is the capital of Norway Reykjavik is the capital of Iceland Copenhagen is the capital of Denmark Cool. So as you can see, the index Question 2.5#What output would the following program produce? Try to first think about the loop without running any code. odd_numbers = [1, 3, 5, 7, 9] even_numbers = [10, 4, 6, 8, 2] for i in range(len(odd_numbers)): print(odd_numbers[i] + even_numbers[i])
# Use this cell to enter your solution.
Footnotes#How do you use a list variable in a for loop in Python?to loop through a list variable. list1 = [2, 4, 3, 7] list2 = [4, 5, 6] list3 = [9, 5, 7, 8, 3, 2, 1] list4 = [4, 1] for i in list1: print (i). or you can put all the lists in a list and loop through it. ... . you can also put all of them in a dictionary structure {key,value}. Can we use list in for loop in Python?In Python, we can loop over list elements with for and while statements, and list comprehensions.
Can we use list in for loop?You can also loop through the list items by referring to their index number. Use the range() and len() functions to create a suitable iterable.
Can a list be a variable in Python?No. A list is an object.
|