Skip to content

Instantly share code, notes, and snippets.

@ruslanmv
Created December 25, 2021 10:27
Show Gist options
  • Save ruslanmv/b7d6dfe28205492e51061a953fe3e661 to your computer and use it in GitHub Desktop.
Save ruslanmv/b7d6dfe28205492e51061a953fe3e661 to your computer and use it in GitHub Desktop.
Tricks with Zip in Python
## Tuple:
# Capture arbitrarily long list
values = 1,2,3,4,5
a, b, *rest = values
# Discard the rest
a, b, *_ = values
## Zip:
# "pairs" up the elements of list
seq1 = ['foo','bar','baz']
seq2 = ['one','two','three']
for i in list(zip(seq1, seq2)):
a,b = i
print('{}-{}'.format(b,a))
# Unzip a sequence
pitchers = [('Nolan','Ryan'),
('Roger','Clemens'),
('Schilling','Curt')]
first_names, last_name = zip(*pitchers)
# Create Dicts from Sequences
mapping = {}
key_list = ['Apple','Orange','Banana']
value_list = [1, 4, 8]
for key, value in zip(key_list, value_list):
mapping[key] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment