Python zip

Python zip


names = ['Peter Parker', 'Clark Kent', 'Wade Wilson', 'Bruce Wayne']

heroes = ['Spiderman', 'Superman', 'Deadpool', 'Batman']

universes = ['Marvel', 'DC', 'Marvel', 'DC']



for name, hero, universe in zip(names, heroes, universes):

    print(f'{name} is actually {hero} from {universe}')



# Peter Parker is actually Spiderman from Marvel

# Clark Kent is actually Superman from DC

# Wade Wilson is actually Deadpool from Marvel

# Bruce Wayne is actually Batman from DC

zip is an iterator and it can be exhausted (emptied)


names = ['Peter Parker', 'Clark Kent', 'Wade Wilson', 'Bruce Wayne']

heroes = ['Spiderman', 'Superman', 'Deadpool', 'Batman']

universes = ['Marvel', 'DC', 'Marvel', 'DC']



identities = zip(names, heroes, universes)



for name, hero, universe in identities:

    print(f'{name} is actually {hero} from {universe}')



print(list(identities)) # [] (because identities was emptied by for-loop)



# solution: to store zip-iterator into variable



identities_list = list(zip(names, heroes, universes))



for name, hero, universe in identities_list:

    print(f'{name} is actually {hero} from {universe}')



print(identities_list) # [('Peter Parker', 'Spiderman', 'Marvel'), ...

Leave a Comment