Skip to content

Commit e801fd8

Browse files
committed
Create using_an_unpythonic_loop.rst.
1 parent 1673d8a commit e801fd8

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
Using an unpythonic loop
2+
========================
3+
4+
Summary
5+
-------
6+
7+
Instead of counting over an index and retrieving the corresponding index
8+
element within the for loop, you should use enumerate to retrieve the
9+
index and list element simultaneously.
10+
11+
Description
12+
-----------
13+
14+
`PEP 20 <http://legacy.python.org/dev/peps/pep-0020/>`_ states "There should be one-- and preferably only one --obvious way to do it." Creating a loop that uses an incrementing index to access each element of a list within the loop construct is not the preferred style for accessing each element in a list. The preferred style is to use ``enumerate()`` to simultaneously retrieve the index and list element simultaneously.
15+
16+
Examples
17+
----------
18+
19+
Loop defines index and accesses each list element with index
20+
............................................................
21+
22+
The module below uses an index variable ``i`` in a ``for`` loop to iterate through the elements of a list. This is not the preferred style for iterating through a list in Python.
23+
24+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
25+
26+
.. code:: python
27+
28+
l = [1,2,3]
29+
30+
for i in range(0,len(list)): # creating index variable
31+
le = l[i] # using index to access list
32+
print i,le
33+
34+
Solutions
35+
---------
36+
37+
Retrieve index and element when defining loop
38+
.............................................
39+
40+
The updated module below demonstrates the Pythonic style for iterating through a list. When you define two variables in a ``for`` loop in conjunction with a call to ``enumerate()`` on a list, Python automatically assigns the first variable as an index variable, and the second variable as the corresponding list element value for that index location in the list.
41+
42+
.. code:: python
43+
44+
for i, le in enumerate(l):
45+
print i, le
46+
47+
References
48+
----------
49+
- `PEP 20 - The Zen of Python <http://legacy.python.org/dev/peps/pep-0020/>`_

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy