Section 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:
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
Checkpoint 9.3.1.
p = [3, 4, "Me", 3, [], "Why", 0, "Tell", 9.3]
for ch in p:
print(ch)
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.
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:
Checkpoint 9.3.2.
Q-4: What will happen if you attempt to traverse an empty list?
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.
Although a list can contain another list, the nested list still counts as a single element. Check out the length of this list:
Checkpoint 9.3.3.
nestedList = [["First", 2, ["Third"]]]
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.