user_df
user_df

Reputation: 43

Zip operator in python

If I use

l = zip((1,2), (3,4))
print(l)

this does not print the output , why do I have to use

print(list(l))

Also what does below code mean, it assigns data to x and y but how

l = zip((1,2), (3,4)) 
x, y = zip(*l)

Upvotes: 2

Views: 105

Answers (3)

Infinite
Infinite

Reputation: 764

1) Zip is an iterator and follows lazy evaluation which means only evaluate when the need arises , so when you print the output of zip it shows the generator its pointing too. when you use list it starts to generate the string/output of the zip generator

2)

 l = zip((1,2),(3,4)) 
    x,y = zip(*l)

This is basically an example of unpacking the variables , run below code it basically unpacks the value you passed to zip

l=zip([1,2],[3,4])
temp = list(l)
x,y = zip(*temp)
print(x)
print(y)

Unpacking variables are not limited to zip , here is another example where you could use it , below I have a function which takes 3 inputs and I have a list with 3 values instead of manually having to pass each argument,I want to just pass the list in one go. Below code will fail

def func_temp(x,y,z):
    print('call to function success')
if __name__ == '__main__':
    lis= [1,2,3]
    func_temp(lis)

    func_temp(lis)
TypeError: func_temp() missing 2 required positional arguments: 'y' and 'z'

Process finished with exit code 1

If I use unpack it will work fine , using unpack operator on lis is going to open up the three variables that are packed in list lis.

def func_temp(x,y,z):
    print('call to function success')

if __name__ == '__main__':
    lis= [1,2,3]
    func_temp(*lis)

*Here is good and short tutorial which talks about packing and unpacking in python in * more detail

Upvotes: 2

K4liber
K4liber

Reputation: 913

Because zip() function returns iterator (https://www.w3schools.com/python/python_iterators.asp).

Upvotes: -1

chepner
chepner

Reputation: 531798

zip creates an iterator, not a list of tuples. print only calls __str__ on its argument, and building a string representation of an instance of zip does not actually consume the iterator. list(l) does; it extracts each value and puts it in a list. list.__str__ then builds the string you want to display.

zip(*l) is an idiom used to transpose a list of sequences. If l == [(1,3), (2,4), then the call zip(*l) is equivalent to zip((1,3), (2,4)), which gives you back the original list. In general, zip(*zip(l)) is roughly equivalent to l itself.

Upvotes: 2

Related Questions