0

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..."

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.

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!

sniperd
  • 5,124
  • 6
  • 28
  • 44
  • 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

2 Answers2

5

This is pythonic :

for _ in my_list:
    call_external_thingy()
Corentin Limier
  • 4,946
  • 1
  • 13
  • 24
  • Interesting! Does the `_` have a special meaning? – sniperd Sep 14 '18 at 13:26
  • it's just like any other variable. you can use it like item but it doesn't stand out too much – Xnkr Sep 14 '18 at 13:27
  • 1
    _ has different purposes in python. https://hackernoon.com/understanding-the-underscore-of-python-309d1a029edc explains some _ usages – Corentin Limier Sep 14 '18 at 13:27
  • isn't it better to loop through a generator though? arent those genraly faster – Jonas Wolff Sep 14 '18 at 13:29
  • @sniperd in this context it's generally understood as a value that has no significance in what you're doing (EDIT: that's in reference to your first comment) – roganjosh Sep 14 '18 at 13:30
  • 1
    @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
  • 1
    @JonasWolff Nope, why make a generator when you already have a list? – PM 2Ring Sep 14 '18 at 13:32
  • Thank you all for the great links and input, this is a great answer and very helpful comments. I didn't know of the `_` convention as a throw-a-way (for lack of a better term). Wonderful! – sniperd Sep 14 '18 at 13:37
  • 1
    @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
-2
for i in range(len(my_list)):
    call_external_thingy()
Noam Hacker
  • 4,671
  • 7
  • 34
  • 55
Nik
  • 1,093
  • 7
  • 26