Help with the Zip function

Can someone please tell me more about the Zip function ? Also what is an iterator ? why do we have to use the list function before the Zip function ?

Hello! The zip() function takes two lists, and puts them together, like a zip:

array_1 = ["h", "e", "l", "l", "o"]
array_2 = ["w", "o", "r", "d", "!"]
z = zip(array_1, array_2)
print(list(z))
#returns
#[('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'd'), ('o', '!')]

An iterable is something that can be iterated over. Often, things are iterated over in a loop:

array_1 = ["l", "o", "o", "p"]
for i in array_1:#here, we are iterating over the array_1 array
  print(i)

You must use list() when using zip() because (I think) that the type of object returned by the zip() function can’t be printed to the console. You can, however, still iterate through them:

array_1 = ["h", "e", "l", "l", "o"]
array_2 = ["w", "o", "r", "d", "!"]
z = zip(array_1, array_2)
for i in z:
    print(i)
#returns
>>('h', 'w')
>>('e', 'o')
>>('l', 'r')
>>('l', 'd')
>>('o', '!')

Here are a few articles for further reading on the zip() method:

  1. programiz
  2. realpython
  3. the Python official docs

I hope this helps!

3 Likes

Hey hello,
thank you so much for your reply. It was really helpful. But I think need to practice a little more and I will definitely take a look at the articles.
Thank you so much :blush:

1 Like