Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python "throw away" variable work?

Tags:

python

Lets say I have:

[obj for (_, obj) in stack]

This code assumes that the first object in stack is a tuple, and throws away the first part of the tuple.

What happens if the code is not a tuple, but a single object?

Does it just ignore the thrown-away part and take the whole object?

like image 377
Richard Garfield Avatar asked Jan 06 '23 08:01

Richard Garfield


1 Answers

_ it's just a convention, any other name will behave same way.

Name _ simply points to first element of unpacked tuple. When that name goes out of scope reference, counter is decreased, there are no other named referencing to "first element of unpacked tuple", and that object may be safely garbage-collected.

Since _ is only convention, attempt to unpack tuple with _ will behave same as with any other name - it'll raise an exception, one of following:

a, b = 1  # TypeError: 'int' object is not iterable
a, b = () # ValueError: need more than 0 values to unpack
a, b = (1, 2, 3) # ValueError: too many values to unpack
like image 116
Łukasz Rogalski Avatar answered Jan 19 '23 08:01

Łukasz Rogalski