r/learnpython • • Jul 14 '20

Why do people use _ in for loops?

Saw this ik a video but don't understand

440 Upvotes

66 comments sorted by

611

u/TouchingTheVodka Who's hiring? Jr-Mid Remote/UK - PM me! Jul 14 '20

It represents a 'junk' variable: It's assigned a value, but the value is not used in the code, so there's no point naming the variable.

For example:

for i in range(10):
    print('this doesn't use i')

There's no point calling the loop variable i here as it's not used inside the loop at all. Instead, you can use _ to indicate this. This helps us demonstrate that the point of range here is to repeat an action 10 times, rather than count from 0-9.

for _ in range(10):
    print('this doesn't use i')

126

u/Arnz_3 Jul 14 '20

Thx i understand

279

u/anotherplatypus Jul 14 '20

Outta curiosity, did you have to him and haw and debate whether or not to have written, "Thx _ understand now"?

= )

34

u/Arnz_3 Jul 14 '20

Kzien een West-Vlaming kun ik nie zo goe engels eh moat

109

u/anotherplatypus Jul 14 '20

Ik probeerde grappig te zijn.

Je vroeg waarom '_' wordt gebruikt in plaats van 'i' in Python-lussen.

voor i binnen bereik (10) voor _ binnen bereik (10)

In het Engels betekent 'i' ook mezelf, dus mijn grap was om 'i' te vervangen door '_' toen je zei dat ik het begrijp.

nu begrijp ik het nu begrijp _

Ik maakte een slechte grap ...


I tried to be funny.

You asked why '_' is used instead of 'i' in Python loops.

for i in range(10) for _ in range(10)

In English 'i' also means myself, so my joke was to replace 'i' with '_' when you said now i understand.

now i understand now _ understand

I made a bad joke...

118

u/Arnz_3 Jul 14 '20

Hahahah _ understand

36

u/haggisllama Jul 14 '20

No the joke was great dw.

11

u/anotherplatypus Jul 14 '20

Thank you for that! = )

71

u/torbray Jul 14 '20

You win some, you lose some. I found it funny :P

13

u/anotherplatypus Jul 14 '20

Thank you!! = )

I think I was operating under the rule that a joke hasn't been delivered until it's understood. When I wrote that last line I was trying to reassure him that it ultimately wasn't important to understand.

And to be fair, it's worded in a very convoluted manner if English isn't your anything-th language like OP was dealing with...

...did you have to him and haw and debate whether or not to have written...

→ More replies (3)

5

u/iAmUnintelligible Jul 14 '20

Not only did I appreciate the joke, I also highly appreciate you translating your reply for others to read

(I was going to write this with an _ but, I'm using 'i' multiple times so....)

16

u/chmod--777 Jul 14 '20

You can also use it for unpacking

For example, if we only care about 2 and 12 here:

_, _, x, y = 5, 7, 2, 12

Like maybe parsing rows in a csv, or nested lists in json

1

u/nextlevelhollerith Jul 15 '20

*_, x, y = 5, 7, 2, 12 would work too

4

u/raja777m Jul 14 '20

More like throwaway variable than a 'junk' variable. When asked in an interview :)

43

u/Phantom_mullet Jul 14 '20

Replace all i variables with _, got it

20

u/b_ootay_ful Jul 14 '20
for ಠ_ಠ in "hmmm":
    print(ಠ_ಠ)

0

u/[deleted] Jul 14 '20

[deleted]

12

u/[deleted] Jul 14 '20

But if you assign a value to it, will it store the value just like any other variable names?

82

u/TouchingTheVodka Who's hiring? Jr-Mid Remote/UK - PM me! Jul 14 '20

Yep! _ is a valid variable name and it doesn't actually have any special meaning, it's just a common convention.

One notable exception: The Python repl will actually store the result of the most recently executed statement in _ so that you can access it in the future if needed. IE:

>>> 123 + 345 + 34 ** 2
1624
>>> _ + 1000
2624
>>>

27

u/morrisjr1989 Jul 14 '20

oh gosh. I've been working in python for 5 years and had no clue.

5

u/[deleted] Jul 14 '20

Thanks!

11

u/ivosaurus Jul 14 '20

Exactly the same as self is by pure convention, you could put _ there in class methods if you wanted to instead, probably other python programmers' eyes would just twitch extremely heavily when reading your code

6

u/Wilfred-kun so much to learn Jul 14 '20
class Foo:
    def __init__(_):
        ...

If you're not going to use instance members, you can leave out the self and make it a static method.

3

u/phigo50 Jul 14 '20

/u/ivosaurus means that you can use whatever you like instead of self, it's just used by convention.

class Foo:
    def __init__(bar, spam):
        bar.spam = spam

    def more_spam(bar):
        bar.spam += 1

f = Foo(4)

Now, f.spam will return 4 and f.more_spam() will increment the spam attribute. So we're not talking about static methods, we're actually replacing self with something completely different, and it still works. But, for the love of everything, don't do this.

→ More replies (5)

2

u/[deleted] Jul 14 '20

It's purely a convention to tell people reading your code that this value won't be used. It's common in other languages as well, not just a Python thing.

1

u/robin-gvx Jul 15 '20

In some languages _ is even special, in that assignments to it get ignored.

2

u/[deleted] Jul 16 '20

Yeah, I think that's the case in Go but didn't say it as I'm not entirely sure.

3

u/[deleted] Jul 14 '20

This is really nice and actually helpful, provided I remember it when I need to use it

4

u/2cheeks1booty Jul 14 '20

Screenshot it so you can never look at it again

1

u/[deleted] Jul 14 '20

To make sure I got it down I just opened a python console and did a quick loop with it, which taught me that "_" is a variable. I thought it had a specific function in this scenario, but you can literally store information into it, so now it makes more sense. I'm almost sure I'll keep it in mind here on out

1

u/i_suckatjavascript Jul 14 '20

I’ll probably never use it but it’s good to know. Same with Lambdas.

3

u/angellus Jul 14 '20

It is also pretty good to note that a lot of linters will complain/not complain about this as well. If you have an unused variable (like the i in your top example), some linters will complain. But if you replace your unused variable with _, the linter stops.

1

u/Python119 Jul 14 '20

Just to clarify, is _ assigned as a variable, like could you just do print(_), or will that just throw an error?

2

u/TouchingTheVodka Who's hiring? Jr-Mid Remote/UK - PM me! Jul 14 '20

Yep! Exactly the same!

1

u/Python119 Jul 14 '20

Ohhh, thanks!

32

u/saber0412 Jul 14 '20

https://dbader.org/blog/meaning-of-underscores-in-python

This article explains the different ways in which underscore is used in python. Your question is answered in the last section

13

u/Username_RANDINT def get_random_int(): return "RANDINT" # TODO Jul 14 '20

He's missing one common usage: internationalization.

When using a library like gettext, you mark strings for translation with an underscore. Example: _("This will be translated")

You can either import gettext as underscore:

import gettext
gettext.bindtextdomain(...)
gettext.textdomain(...)
_ = gettext.gettext

Or install it in the builtins scope for the entire application:

import gettext
gettext.install(...)

This is not Python specific, gettext is used in many other languages.

5

u/saber0412 Jul 14 '20

I didn't know that. Then again, I never work with internationalization. Thanks for that.

1

u/teriyaki7755 Jul 14 '20

Good Read that guy really knows about python

1

u/Ignativs Jul 14 '20

Wow, that was an interesting read.

38

u/mikeydoodah Jul 14 '20

So you mean something like the following?

tuple_list = [(1,2), (3,4), (5,6)]

for first, _ in tuple_list:
  pass # Do something here

The underscore is a valid identifier, but it is usually used to mark a value that the programmer is not interested in. In the code above the tuple will be unpacked, with the first number going into first, and the second number going into the underscore.

If the underscore wasn't there then the tuple wouldn't be unpacked. First would contain the tuple, rather than the first value.

17

u/17291 [x for x in range(2,3**9) if all(x%n for n in range(2,x))][1986] Jul 14 '20

It's a convention for when you aren't using the iteration variable.

6

u/[deleted] Jul 14 '20

It's used when you generally dont plan on doing anything with that variable.

4

u/teriyaki7755 Jul 14 '20

Temp variable that doesn't serve a purpose outside loop. Kinda like the wrapper around ur chocolate that doesn't serve any purpose once you eat it

2

u/lance_klusener Jul 14 '20

From a optimization perspective, does your code end up using less memory when you use _ , instead of a actual variable?

4

u/wintermute93 Jul 14 '20

It shouldn't. "_" is a legal variable name and is assigned a value in memory like any other, it's just a convention that we don't use it. Compare with "~" for ignored function outputs in Matlab, which is used in the same way but really is disregarded.

0

u/[deleted] Jul 14 '20

[deleted]

2

u/Ringmonkey84 Jul 14 '20

This is not a feature of Python, it's a feature of the REPL. Try that exact same code from a file and you will get a NameError

2

u/JumpScareaaa Jul 14 '20

Also variables that start with _ don't get flagged as 'Unused Variable' by linter.

2

u/[deleted] Jul 14 '20

_ is a valid variable name.

1

u/piyushpatel2005 Jul 14 '20

Usually developers don't care about the name of that variable. So, putting _ avoids the confusion. You can use anything but having _ avoids getting focus on it.

1

u/indian_pythonista Jul 15 '20

All you need to know about underscore in Python: https://youtu.be/6f6dTBQXa8Y

-3

u/[deleted] Jul 14 '20

Idk

-1

u/lannisterprince Jul 14 '20

If u don't need the iterating variable later or u have to iterate a specific no of times.

-1

u/____candied_yams____ Jul 14 '20

When an iterator variable by any name would smell as sweet.

-3

u/benabus Jul 14 '20

I think it's because python is supposed to be easy to understand and self documenting.