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)

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://stackoverflow.com/documentation/python/809/incompatibilities-between-python-2-and-python-3/8186/map) in http://stackoverflow.com/documentation/python/809/incompatibilities-between-python-2-and-python-3 ).

Feedback about page:

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


List:
* List
* Iterating over lists

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve