zip a list python code example

Example 1: python zip function

>>> numbers = [1, 2, 3]
>>> letters = ['a', 'b', 'c']
>>> zipped = zip(numbers, letters)
>>> zipped  # Holds an iterator object
<zip object at 0x7fa4831153c8>
>>> type(zipped)
<class 'zip'>
>>> list(zipped)
[(1, 'a'), (2, 'b'), (3, 'c')]  #list of tuples  
# zip returns tuples

Example 2: python zip a list of lists

# Basic syntax:
list(zip(*[[list], [of], [lists]]))
# Where zip is used to join iterable items together by corresponding
#	iterated elements

# Example usage 1:
list_of_lists = [[1,2], [3,4], [5,6]]
list(zip(*list_of_lists))
--> [(1, 3, 5), (2, 4, 6)] 

# Example usage 2:
list_of_lists = [[1,2], ['a',4], [5,6,7]]
list(zip(*list_of_lists))
--> [(1, 'a', 5), (2, 4, 6)] # Note that the extra element in [5, 6, 7]
#	was ignored.

Example 3: zip listas python

>>> meses = ["marzo", "abril", "mayo"]
>>> estados = ["ventoso", "lluvioso", "florido y hermoso"]
>>> for mes, estado in zip(meses, estados):
...     print(mes, estado)
...
marzo ventoso
abril lluvioso
mayo florido y hermoso