Skip to content

Instantly share code, notes, and snippets.

@leveled
Created February 22, 2021 00:49
Show Gist options
  • Save leveled/b46145960f232f850cf357c6867497b1 to your computer and use it in GitHub Desktop.
Save leveled/b46145960f232f850cf357c6867497b1 to your computer and use it in GitHub Desktop.
Asterisk unpacking cheatsheet in Python
#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