To iterate through a list you can use for
:
for x in ['one', 'two', 'three', 'four']:
print(x)
This will print out the elements of the list:
one
two
three
four
The range
function generates numbers which are also often used in a for loop.
for x in range(1, 6):
print(x)
The result will be a special range sequence type in python >=3 and a list in python <=2. Both can be looped through using the for loop.
1
2
3
4
5
If you want to loop though both the elements of a list and have an index for the elements as well, you can use Python's enumerate
function:
for index, item in enumerate(['one', 'two', 'three', 'four']):
print(index, '::', item)
enumerate
will generate tuples, which are unpacked into index
(an integer) and item
(the actual value from the list). The above loop will print
(0, '::', 'one')
(1, '::', 'two')
(2, '::', 'three')
(3, '::', 'four')
Iterate over a list with value manipulation using map
and lambda
, i.e. apply lambda function on each element in the list:
x = map(lambda e : e.upper(), ['one', 'two', 'three', 'four'])
print(x)
Output:
['ONE', 'TWO', 'THREE', 'FOUR'] # Python 2.x
NB: in Python 3.x map
returns an iterator instead of a list so you in case you need a list you have to cast the result print(list(x))
(see http://www.riptutorial.com/python/example/8186/map-- in http://www.riptutorial.com/python/topic/809/incompatibilities-moving-from-python-2-to-python-3 ).