For loops

suggest change

for loops iterate over a collection of items, such as list or dict, and run a block of code with each element from the collection.

for i in [0, 1, 2, 3, 4]:
    print(i)

The above for loop iterates over a list of numbers.

Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2, etc. The output will be as follow:

0  
1
2
3
4

range is a function that returns a series of numbers under an iterable form, thus it can be used in for loops:

for i in range(5):
    print(i)

gives the exact same result as the first for loop. Note that 5 is not printed as the range here is the first five numbers counting from 0.

Iterable objects and iterators

for loop can iterate on any iterable object which is an object which defines a __getitem__ or a __iter__ function. The __iter__ function returns an iterator, which is an object with a next function that is used to access the next element of the iterable.

Feedback about page:

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


Loops:
* Loops
* For loops

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