The easiest way to traverse the elements of a list is
with a for loop. The principle is the same as for a string.
>>> for guitar in guitars: ... print guitar ... Gibson Fender Jackson
This
is ok if you want to read the elements of the list. But if you want to write or
update the elements, you have to apply indices. A common way is to combine the
built-in function like range and len with for loop.
>>> numbers = [1, 2, 3, 4, 5] >>> for i in range(len(numbers)): ... numbers[i] = numbers[i]**2 ... >>> numbers [1, 4, 9, 16, 25]
This
for loop goes through 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:
>>> emptylist [] >>> for x in emptylist: ... print 'This never happens' ...
Nema komentara:
Objavi komentar