Created
February 22, 2021 00:49
-
-
Save leveled/b46145960f232f850cf357c6867497b1 to your computer and use it in GitHub Desktop.
Asterisk unpacking cheatsheet in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Unpack tuples | |
>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] | |
>>> first, second, *remaining = fruits | |
>>> remaining | |
['watermelon', 'tomato'] | |
>>> first, *remaining = fruits | |
>>> remaining | |
['pear', 'watermelon', 'tomato'] | |
>>> first, *middle, last = fruits | |
>>> middle | |
['pear', 'watermelon'] | |
#Unpack list literals | |
def palindromify(sequence): | |
return [*sequence, *reversed(sequence)] | |
def rotate_first_item(sequence): | |
return [*sequence[1:], sequence[0]] | |
#Unpack dictionaries | |
>>> date_info = {'year': "2020", 'month': "01", 'day': "01"} | |
>>> track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'} | |
>>> all_info = {**date_info, **track_info} | |
>>> all_info | |
{'year': '2020', 'month': '01', 'day': '01', 'artist': 'Beethoven', 'title': 'Symphony No 5'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment