3.10 Modifying Lists Through Loops
Consider the following code block:
= [1346, 1665, 1855]
years
for i in years:
= i - 5
i
print(years)
## [1346, 1665, 1855]
Notice that running this code block does not change the underlying list. When you run this for loop, the following happens:
i
is set equal to the value of the corresponding value fromyears
- We subtract 5 from
i
and update the value ofi
- We do not do anything with this updated
i
- the original list,years
, is not modified
What if we want to loop through years and update each vallue in the process. There are two ways of doing this:
3.10.1 Appending to an empty list
One way is to loop through your list, update each value, and then add it to the end of a new list. Look at the code below.
= [1346, 1665, 1855]
years = [] # Initialize a new list to store updated values
updatedYears
for i in years:
= i - 5
i # Add updated value to the end of your new list
updatedYears.append(i)
print(updatedYears)
## [1341, 1660, 1850]
Here is how the for
loop works:
i
is set equal to the value of the corresponding value fromyears
- We subtract 5 from
i
and update the value ofi
- We save this new value of
i
by adding it in to a new list
At the end of this loop, we have two lists:
years
, which contains original valuesupdatedYears
, which contains updated values (original values - 5)
3.10.2 Looping through indices
Another way to update these values is to assign them back into the original list using the following syntax:
<index>] = <new value> years[
For this, we need to iterate through the indices of years
.
= [1346, 1665, 1855]
years
for i in range(len(years)): # Loop through the positions of years
= years[i] - 5 # Extract the appropriate value from years and subtract 5 from it, storing it as a new variable
newValue = newValue # Add updated value back into years
years[i]
print(years)
## [1341, 1660, 1850]
Breaking this down:
- We loop through a range from 0 to the length of
years
. I.e. here, we would loop through the values0
,1
,2
- We extract the value from years at our current position using
years[i]
- We update this value by subtracting 5 from it. Updated value is saved as
newValue
- We add this new value back into
years
at the original position
At the end of this loop, we have one list, years
, which no longer contains its initial values. years
now contains our updated values.