I'm trying to understand the difference between zip()
and zip(*)
.
From what I understand, zip()
can be used to combine two lists, such that elements with a shared index are together. Such as in these examples:
dict_list = {'First Name': ['Tom', 'Ann', 'Ben'],
'Last Name': ['Haverford', 'Perkins', 'Wyatt'],
'Age': [33, 42, 44],
'Occupation': ['Administrator', 'Nurse', 'Auditor']}
for first_name, last_name, age, occupation in zip(dict_list['First Name'], dict_list['Last Name'], dict_list['Age'], dict_list['Occupation']):
print(first_name, last_name, age, occupation)
#result
Tom Haverford 33 Administrator
Ann Perkins 42 Nurse
Ben Wyatt 44 Auditor
So why does it seem to me that sometimes, zip(*) behaves this way? For example:
for t in (zip(*dict_list.values())):
print(t)
#result
('Tom', 'Haverford', 33, 'Administrator')
('Ann', 'Perkins', 42, 'Nurse')
('Ben', 'Wyatt', 44, 'Auditor')
Since my dict_list.values()
are lists, it seems like zip(*)
placed all elements with shared indexes in the same tuple. Which is not that much different from the first code, in which I used zip()
in a for
loop with dict keys passed into it and with corresponding looping variables
How are zip()
and zip(*)
behaving in this case?