Python syntax star-underscore (*_)

r,c,*_ = im.shape from transforms.py

what does *_ means? I have been using python for few years but I have never seen this syntax before.

=====

found it.

$ python
Python 3.6.5 (default, Mar 30 2018, 06:41:53) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a, *_ = (1,2,3)
>>> a
1
6 Likes

I didn’t know either :slight_smile:
More examples here: https://www.python.org/dev/peps/pep-3132/
Looks like it is added in Python3

I think it is a combination of * and the _. You can see the * in action here

In short, it does this (Its called Extended Iterable Unpacking I believe):

And the _ is just a placeholder - it means throw whatever you would assign to this if it was a variable away.

4 Likes

My understanding is that _ doesn’t actually “throw away” the values.

a, *_ = [0, 1, 2, 3]
a == 0
_ == [1, 2, 3]

That means whatever you put in there will still take up memory. For most situations this shouldn’t matter.

(To put it another way, the Python garbage collector doesn’t seem to treat the _ variable in a special way, so it keeps the data in memory as long as something references it.)

3 Likes

How about this line? accuracy_np(*m3.predict_with_targs()) from lesson 4.

whats this * means here?

predict_with_targs probably returns a tuple or a list, by using the * components of the iterable get passed as individual arguments to to accuracy_np

1 Like

Since numpy’s ndarray shape attribute yields a tuple of dimensions, this is assigning the first dimension as r (row), second as c (column), and any remaining (using *) dimensions to _.
Unpacking the tuple in the code snippet in the OP, _ would return a list of [2, 3]. From im.shape _ would return a list of remaining dimensions, or an int if there is only one left.

Additionally, it looks like @tester is in the terminal, so even though it’s not used this way here, _ can be used to reference the value of the last executed expression.

Dan Bader has a good article on underscores in python.

And there’s this SO answer by Python core developer Nick Coghlan.

1 Like