The zip function can take values from 2 lists and create tuples that forms pairs of values.
>>> L1 = [ 1 ,2 , 3 , 4 ]
>>> L2 = [ 5 , 6, 7, 8 ]
>>> list( zip( L1,L2) )
[(1, 5), (2, 6), (3, 7), (4, 8)]
If the number of elements in the lists are different then the number of tuples in the resulting list will be the number of elements in the smaller list.
>>> L1 = [ 1 ,2 ]
>>> L2 = [ 5 , 6, 7,8 ]
>>>
>>> list( zip( L1, L2 ) )
[(1, 5), (2, 6)]
We can use the zip function to create dictionaries.
>>> keys = [ 1 ,2 ,3 ]
>>> values = [ "one" , "two" , "three" ]
>>> d1 = dict( zip(keys, values ) )
>>> d1
{1: 'one', 2: 'two', 3: 'three'}
File1: map1.py
def function_square( x1):
return ( x1 * x1 )
items1 = [ 1 ,3 , 5, 7 ]
list1 = list( map(function_square, items1 ) )
print( list1 )
Output:
[amittal@hills chapter13]$ python3 map1.py
[1, 9, 25, 49]