Is using range() in for loops really Pythonic?

Paddy paddy3118 at googlemail.com
Sun May 11 01:19:10 EDT 2008


On May 11, 3:19 am, John Salerno <johnj... at NOSPAMgmail.com> wrote:
> I know it's popular and very handy, but I'm curious if there are purists
> out there who think that using something like:
>
> for x in range(10):
>     #do something 10 times
>
> is unPythonic. The reason I ask is because the structure of the for loop
> seems to be for iterating through a sequence. It seems somewhat
> artificial to use the for loop to do something a certain number of
> times, like above.
>
> Anyone out there refuse to use it this way, or is it just impossible to
> avoid?

Hi John,
If you have an object that is both indexable and iterable, then
visiting every member by first generating an index then indexing the
object is un-pythonic. You should just iterate over the object.

Like most rules, things can get fuzzy around the edges: if you have n
objects to be visited each index at a time, then the more functional
approach would be to izip all the objects and iterate over the result.
Another way would be to iterate over the the enumeration of one object
and use the index created to index the other n-1 objects.

In all such situations you need to remember that things such as code
clarity, and speed, might make the final decision for you.


In the following examples then the first is what I would use, izip. If
I needed an index then I'd prefer the last, which combines izip and
enumerate:

PythonWin 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin'
for further copyright information.

 >>> obj1 = 'CSM'
 >>> obj2 = 'aue'
 >>> obj3 = 'tmn'
 >>> from itertools import izip
 >>> for x,y,z in izip(obj1, obj2, obj3):
 ... 	print x,y,z
 ...
 C a t
 S u m
 M e n
 >>> for i,x in enumerate(obj1):
 ... 	print x, obj2[i], obj3[i]
 ...
 C a t
 S u m
 M e n
 >>> for i in range(len(obj1)):
 ... 	print obj1[i], obj2[i], obj3[i]
 ...
 C a t
 S u m
 M e n
 >>> for i,(x,y,z) in enumerate(izip(obj1, obj2, obj3)):
 ... 	print i, x, y, z
 ...
 0 C a t
 1 S u m
 2 M e n
 >>>


- Paddy.



More information about the Python-list mailing list