Explain the zip()function from Iterators & Generators. __________________ DONT SPAM! NEED CORRECT ANSWERS. Thanks ♥ :D
Answers
The zip () function :-
The zip() function accepts an arbitrary number of iterables and returns a zip object which is an iterator of tuples. For example:
In [] : company_names = ['Apple', 'Microsoft', 'Tesla']
In [] : tickers = ['AAPL', 'MSFT', 'TSLA']
In [] : z = zip(company_names, tickers)
In [] : print(type(z))
<class 'zip'>
Here, we have two lists company_names and tickers. Zipping them together creates a zip object which can be then converted to list and looped over.
In [] : z_list = list(z)
In [] : z_list
Out[]: [('Apple', 'AAPL'), ('Microsoft', 'MSFT'),
('Tesla', 'TSLA')]
• The first element of the z_list is a tuple which contains the first element of each list that was zipped.
• The second element in each tuple contains the corresponding element of each list that was zipped and so on.
Alternatively, we could use a for() loop to iterate over a zip object print the tuples.
In [] : for company, ticker in z_list:
...: print(f'{ticker} = {company}')
AAPL = Apple
MSFT = Microsoft
TSLA = Tesla
We could also have used the splat operator(*) to print all the elements.
In [] : print(*z)
('Apple', 'AAPL') ('Microsoft', 'MSFT') ('Tesla', 'TSLA')