9.3. Traversing a listΒΆ
The most common way to traverse the elements of a list is with a
for
loop. The syntax is the same as for strings:
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
This works well if you only need to read the elements of the list. But
if you want to write or update the elements, you need the indices. A
common way to do that is to combine the functions range
and
len
:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
- 8
- Iteration by item will process once for each item in the sequence, even the empty list.
- 9
- Yes, there are nine elements in the list so the for loop will iterate nine times.
- 15
- Iteration by item will process once for each item in the sequence. Each string is viewed as a single item, even if you are able to iterate over a string itself.
- Error, the for statement needs to use the range function.
- The for statement can iterate over a sequence item by item.
Q-2: How many times will the for loop iterate in the following statements?
p = [3, 4, "Me", 3, [], "Why", 0, "Tell", 9.3]
for ch in p:
print(ch)
This loop traverses the list and updates each element. len
returns the number of elements in the list. range
returns a
list of indices from 0 to n-1, where n is the length of the list.
Each time through the loop, i
gets the index of the next
element. The assignment statement in the body uses i
to
read the old value of the element and to assign the new value.
A for
loop over an empty list never executes the body:
- The loop will run once.
- The loop will not run because the initial conditions are not met. You cannot traverse over nothing.
- Nothing will happen.
- Nothing will happen when traversing through an empty loop because there are no elements to iterate through.
- It will cause an error.
- It is legal to call this, but nothing will happen. It will not call an error.
- The list will add items to traverse.
- Python will not add items to the list so it is no longer empty, empty lists are okay.
Q-4: What will happen if you attempt to traverse an empty list?
Although a list can contain another list, the nested list still counts as a single element. Check out the length of this list:
- 3
- Remember that the length of a list is only the elements in the outside list.
- 1
- There is technically only one element in this list, but that element has its own items.
- 2
- Remember that the length of a list is only the elements in the outside list.
Q-6: How many items are in nestedList
?
nestedList = [["First", 2, ["Third"]]]