11.1. Zip#
Used to link two lists just like physical zip
11.1.1. Syntax#
zip(list1,list2)
Takes lists
Gives tupple by default
list1=[1,2,3,4]
list2=['A','B','C','D']
list(zip(list1,list2)) # returns iterable obj <> which is tuple by default but can be converted to list as well
[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D')]
11.1.2. Unequal Length Lists#
id=[2,3]
name=['A','B','C','D']
list(zip(id,name)) # It will give only for 2 and 3
[(2, 'A'), (3, 'B')]
id=[2,3,4]
name=['A','B']
list(zip(id,name)) # It will give only for 2 and 3
[(2, 'A'), (3, 'B')]
11.1.2.1. Solution - Use zip_longest from itertools#
from itertools import zip_longest
id=[2,3,4,5]
name=['A','B','C']
print(list(zip_longest(id,name)))
# assigns none for not found keys
#by default which can be replaced by other values as well using fillvalue
print(list(zip_longest(id,name,fillvalue='Not found')))
[(2, 'A'), (3, 'B'), (4, 'C'), (5, None)]
[(2, 'A'), (3, 'B'), (4, 'C'), (5, 'Not found')]
id=[2,3,4]
name=['A','B','C','D']
print(list(zip_longest(id,name)))
# assigns none for not found keys
#by default which can be replaced by other values as well using fillvalue
print(list(zip_longest(id,name,fillvalue='Not found')))
[(2, 'A'), (3, 'B'), (4, 'C'), (None, 'D')]
[(2, 'A'), (3, 'B'), (4, 'C'), ('Not found', 'D')]
11.2. Use case#
# All the if conditions can be applied since it is list comprehension
11.2.1. Creating dictionary from list#
dict(zip(list1,list2))
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}