December 2017
Beginner
412 pages
10h 8m
English
The loops over lists that we have written so far have been used to access list items. But what if we want to change the items in a list? For example, suppose we want to double all of the values in a list. The following doesn’t work:
| | >>> values = [4, 10, 3, 8, -6] |
| | >>> for num in values: |
| | ... num = num * 2 |
| | ... |
| | >>> values |
| | [4, 10, 3, 8, -6] |
Each loop iteration assigned an item in the list values to variable num. Doubling that value inside the loop changes what num refers to, but it doesn’t mutate the list object. For example, after one iteration of the loop, the list is unchanged and num refers to 8 (twice its original value):
Let’s ...
Read now
Unlock full access