Every day I love python more and more.
Today, I was writing some code like:
for i in xrange(N):
do_something()
I had to do something N times. But each time didn't depend on the value of i
(index variable).
I realized that I was creating a variable I never used (i
), and I thought "There surely is a more pythonic way of doing this without the need for that useless index variable."
So... the question is: do you know how to do this simple task in a more (pythonic) beautiful way?
I found the various answers really elegant (especially Alex Martelli's) but I wanted to quantify performance first hand, so I cooked up the following script:
I also came up with an alternative solution that builds on Martelli's one and uses
map()
to call the payload function. OK, I cheated a bit in that I took the freedom of making the payload accept a parameter that gets discarded: I don't know if there is a way around this. Nevertheless, here are the results:so using map yields an improvement of approximately 30% over the standard for loop and an extra 19% over Martelli's.
The _ is the same thing as x. However it's a python idiom that's used to indicate an identifier that you don't intend to use. In python these identifiers don't takes memor or allocate space like variables do in other languages. It's easy to forget that. They're just names that point to objects, in this case an integer on each iteration.
What about a simple while loop?
You already have the variable; why not use it?
A slightly faster approach than looping on
xrange(N)
is:Assume that you've defined do_something as a function, and you'd like to perform it N times. Maybe you can try the following:
I just use
for _ in range(n)
, it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.