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
>>> _ = 'Alice'
>>> print(_)
Alice
2.1.2. Single Underscore
>>> def get_user_from_database(user_id):
... return 'alice', 'secret', 'alice@example.com', 'alice@example.edu'
>>>
>>>
>>> username, password, email_priv, email_work = get_user_from_database(1)
>>> username, _, email_priv, email_work = get_user_from_database(1)
2.1.3. Multiple Underscores
>>> def get_user_from_database(user_id):
... return 'alice', 'secret', 'alice@example.com', 'alice@example.edu'
>>>
>>>
>>> username, password, email_priv, email_work = get_user_from_database(1)
>>> username, password, _, _ = get_user_from_database(1)
>>> username, _, _, email = get_user_from_database(1)
>>> username, _, email, _ = get_user_from_database(1)
2.1.4. For Loop
>>> for _ in range(0,3):
... print('hello')
...
hello
hello
hello
2.1.5. Recap
_
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.6. Use Case - 1
>>> line = 'alice:x:1000:1000:Alice:/home/alice:/bin/bash'
>>> username, _, uid, _, _, home, _ = line.split(':')
>>>
>>> print(f'{username=}, {uid=}, {home=}')
username='alice', uid='1000', home='/home/alice'
2.1.7. 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.8. 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))