Iterating over lists

suggest change

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)

range returns a range object in Python 3, not a list (it returned a list in Python 2). Both can be iterated with for. The loop above prints:

1
2
3
4
5

If you want to loop through 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)

In Python 3, map returns an iterator instead of a list, so print(x) shows a map object. When you need a list, call print(list(x)).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents