One of the biggest advantages of Python is the large set of tools it provides for working with its data types. When working with several lists, it’s sometimes necessary to loop over them and do some operations based on the values of all the lists. This can be done by iterating over indices and then accessing the elements, or by using the built-in
heights = [180, 190, 178] weights = [89, 92, 77] for i in range(len(heights)): h, w = heights[i], weights[i] print(h, '=>', w)
heights = [180, 190, 178] weights = [89, 92, 77] for h, w in zip(heights, weights): print(h, '=>', w)
zipfunction creates tuples from the elements of the lists passed to it. It can handle an arbitrary number of lists. So, we can have
zip(list1, list2, list3, ..., listn). It will create tuples, each containing
nelements if there are
nlists passed to the
Note that it zips the elements up until the shortest list. Therefore if we provide two lists where one is shorter than the other, the last extra elements of the second one will be ignored.
If we would like to be strict about it and not allow trimming the longer lists, we can tell Python to throw an error if that happens by providing an additional
heights = [180, 190] names = ['Bob', 'Liza', 'Anna'] for h, name in zip(heights, names, strict=True): print(name, '=>', h) # ValueError: zip() argument 2 is longer than argument 1
The input contains 3 lists each on a separate line. The elements of the lists are separated by a space. It’s guaranteed that the lists have the same number of elements.
The program should print a new list that contains the product of those 3 lists.
1 2 3 4 5 6 1 1 1
4 10 18