pythonic way to do something N times without an index variable?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 Question
00:32 Accepted answer (Score 127)
00:47 Answer 2 (Score 64)
01:02 Answer 3 (Score 55)
01:22 Answer 4 (Score 11)
01:41 Thank you
--
Full question
https://stackoverflow.com/questions/2970...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#codingstyle #forloop #python
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 Question
00:32 Accepted answer (Score 127)
00:47 Answer 2 (Score 64)
01:02 Answer 3 (Score 55)
01:22 Answer 4 (Score 11)
01:41 Thank you
--
Full question
https://stackoverflow.com/questions/2970...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#codingstyle #forloop #python
#avk47
ACCEPTED ANSWER
Score 131
A slightly faster approach than looping on xrange(N) is:
import itertools
for _ in itertools.repeat(None, N):
do_something()
ANSWER 2
Score 69
Use the _ variable, like so:
# A long way to do integer exponentiation
num = 2
power = 3
product = 1
for _ in range(power):
product *= num
print(product)
ANSWER 3
Score 11
since function is first-class citizen, you can write small wrapper (from Alex answers)
def repeat(f, N):
for _ in itertools.repeat(None, N): f()
then you can pass function as argument.
ANSWER 4
Score 10
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.