loop a list - length of list but do not need the item created, pythonic? [duplicate]
loop a list - length of list but do not need the item created, pythonic? [duplicate]
This question already has an answer here:
This is going to be a bit silly of a question. I have a simple list:
my_list = ["apple", "orange", "car"]
And I'd like to run a loop for the length of that list, but I don't need anything in the list. I can clearly do this:
for item in my_list:
call_external_thingy()
Which would loop 3 times, perfect. However, I'm never using the item
in my for loop. So while this does work, everytime I look at my code I feel that I've made a mistake, "Oh shoot, I didn't pass item
in.. oh right I just need to run that command for the number of items in the list..."
item
item
What would be the more pythonic way to simply run a for loop for the number of items in a list without creating item
. I'm thinking of something with len
or range
but can't get my head around it and anything I mock up just looks like a big mess.
item
len
range
Note, I'm tempted to put this on codereview instead, but they usually want all the code and a lot of why. This seems like a simple enough question to be here, but I could be wrong!
Thank you!
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
2 Answers
2
This is pythonic :
for _ in my_list:
call_external_thingy()
Interesting! Does the
_
have a special meaning?– sniperd
Sep 14 '18 at 13:26
_
_ has different purposes in python. hackernoon.com/… explains some _ usages
– Corentin Limier
Sep 14 '18 at 13:27
@sniperd It's just a convention to use
_
to explicitly indicate that you aren't going to use the loop variable. However, in some contexts _
does have other meanings.– PM 2Ring
Sep 14 '18 at 13:31
_
_
@JonasWolff Nope, why make a generator when you already have a list?
– PM 2Ring
Sep 14 '18 at 13:32
@sniperd Sometimes, especially in comprehensions, you see code where
_
is used as a loop variable which then does go on to use _
. But such code is evil! ;)– PM 2Ring
Sep 14 '18 at 13:42
_
_
for i in range(len(my_list)):
call_external_thingy()
You don't need the
0
in the first argument of range, since it will default the starting point to be 0
.– MooingRawr
Sep 14 '18 at 13:29
0
0
Good dupe find! I was searching around quite a bit before posting, but it makes sense that somebody else already asked this :)
– sniperd
Sep 14 '18 at 15:11