2.1. Syntax Underscore
_
is used to skip valuesIt is a regular variable name, not a special Python syntax
By convention it is used for data we don't want to access in future
It can be used multiple times in the same statement
2.1.1. Syntax
Underscore (
_
) is a regular variable nameIt's not a special Python syntax
By convention it is used for data we don't want to access in future
>>> _ = 'Mark'
>>> print(_)
Mark
2.1.2. Single Underscore
>>> line = 'Mark,Watney,mwatney@nasa.gov,mwatney@gmail.com'
>>>
>>> firstname, lastname, email, _ = line.split(',')
>>> print(firstname)
Mark
>>>
>>> print(lastname)
Watney
>>>
>>> print(email)
mwatney@nasa.gov
Underscore is just like a normal variable, however by convention you should not use it in further code:
>>> print(_)
mwatney@gmail.com
2.1.3. Multiple Underscores
>>> line = 'Mark,Watney,mwatney@nasa.gov,mwatney@gmail.com'
>>>
>>> firstname, lastname, _, _ = line.split(',')
>>> print(firstname)
Mark
>>>
>>> print(lastname)
Watney
In this example, the use of multiple underscores will cause them to overwrite the following ones:
>>> print(_)
mwatney@gmail.com
2.1.4. Use Case - 1
>>> line = 'watney:x:1000:1000:Mark Watney:/home/mwatney:/bin/bash'
>>> username, _, uid, _, _, home, _ = line.split(':')
>>>
>>> print(f'{username=}, {uid=}, {home=}')
username='watney', uid='1000', home='/home/mwatney'
2.1.5. Use Case - 2
Skip
>>> a, b, _ = 'red', 'green', 'blue'
>>> a, _, _ = 'red', 'green', 'blue'
>>> a, _, c = 'red', 'green', 'blue'
>>> _, b, _ = 'red', 'green', 'blue'
>>> _, _, c = 'red', 'green', 'blue'
2.1.6. Use Case - 3
>>> _, important, _ = 1, 2, 3
>>>
>>> print(important)
2
>>> _, (important, _) = [1, (2, 3)]
>>>
>>> print(important)
2
>>> _, _, important = (True, [1, 2, 3, 4], 5)
>>>
>>> print(important)
5
>>> _, _, important = (True, [1, 2, 3, 4], (5, True))
>>>
>>> print(important)
(5, True)
>>>
>>> _, _, (important, _) = (True, [1, 2, 3, 4], (5, True))
>>>
>>> print(important)
5
Python understands this as:
>>> _ = (True, [1, 2, 3, 4], (5, True))
>>>
>>> a,b,c = (object, object, object)
>>> a,b,(c,d) = (object, object, (object,object))