There is an idiom of using a lone underscore for a variable name as a way of indicating that one does care about the value assigned to the variable and will not use it. There is also some play with tuple unpacking below.


In [1]:
from random import randint

In [2]:
# This is a classic use of the lone underscore.
[randint(1, 10) for _ in range(5)]


Out[2]:
[1, 2, 3, 3, 6]

In [3]:
t = (12, 34, 56, 78, 90)

In [4]:
# A crummy example of using '_' to unpack on a single value from a tuple
a, _, _, _, _ = t
a


Out[4]:
12

In [5]:
# When extracting only one item, just index it.
a = t[0]
a


Out[5]:
12

In [6]:
# Repeating a variable on the left side works.
# The last value unpacked is the one that endures.
# Of course, this just disgusting.
# _, _, _, b, a = t would be better,
# and perhaps b, a = t[3:] would be better yet.
# b, a = t[-2:]
a, b, a, b, a = t
a, b


Out[6]:
(90, 78)

In [7]:
# Another example of sparse unpacking.
a, _, b, _, c = t
a, b, c


Out[7]:
(12, 56, 90)

In [8]:
# However, other techniques might be more appropriate.
a, b, c = t[::2]
a, b, c


Out[8]:
(12, 56, 90)

In [9]:
# What technique would you use to improve on the sparse unpacking below?
a, _, _, b, c = t
a, b, c


Out[9]:
(12, 78, 90)