Joining each list values with zip

By: summonagus ● at Aug. 25, 2017, 8:10 a.m. ● and modified at Aug. 25, 2017, 8:10 a.m.
Posted under: #Tricks, #Looping, #Beginner ● Your ip address: 54.224.184.33 ● views: 27 times.

AD Space Available, Book Now!

Here we use zip to iterate over the two containers in parallel.

>>> countries = ['Indonesia', 'India', 'Denmark', 'Singapore']    # 4 length
>>> statements = ['is Great', 'is WOW', 'is Good', 'is Awesome']  # 4 length
>>> 
>>> for country, statement in zip(countries, statements):
...     print(country, statement)
... 
Indonesia is Great
India is WOW
Denmark is Good
Singapore is Awesome
>>>

But, how if one of both have different length? an example like bellow:

>>> countries = ['Indonesia', 'India', 'Denmark']                # 3 length
>>> statements = ['is Great', 'is WOW', 'is Good', 'is Awesome'] # 4 length
>>> 
>>> for country, statement in zip(countries, statements):
...     print(country, statement)
... 
Indonesia is Great
India is WOW
Denmark is Good
>>> 
>>> countries = ['Indonesia', 'India', 'Denmark', 'Singapore']  # 4 length
>>> statements = ['is Great', 'is WOW', 'is Good']              # 3 length
>>> 
>>> for country, statement in zip(countries, statements):
...     print(country, statement)
... 
Indonesia is Great
India is WOW
Denmark is Good
>>>

Now we know, zip only put each shortest list values. Hope it useful..

Author

summonagus

Python Developer, Linux Enthusiast, and Senior writer at python.web.id
Website: https://github.com/agusmakmun
blog comments powered by Disqus