zip() function does not work as expected - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: zip() function does not work as expected (/thread-7962.html) |
zip() function does not work as expected - AyCaramba - Jan-31-2018 This is my code for creating 2 lists, zipping them together, unzipping them and printout the unzipped lists. list1 = [1, 2, 3] # create 2 lists: list1, list2 list2 = ['A', 'B', 'C'] zipped = zip(list1, list2) # create zip object from the 2 lists: zipped test1, test2 = zip(*zipped) # unzip the zip: test1, test2 print(list(test1)) print(list(test2))As expected, I get the output: Now, I want to print the values of zipped, using list(zipped) after defining my zip object. After line 3, I insert the additional print command.list1 = [1, 2, 3] # create 2 lists list2 = ['A', 'B', 'C'] zipped = zip(list1, list2) # create zip object from the 2 lists: zipped print(list(zipped)) test1, test2 = zip(*zipped) # unzip the zip using * print(list(test1)) print(list(test2))I get an error massage: Why do I get an error? Does the list(zipped) command in line 4 somehow destroy my zip object?When I recreate zipped in line 5, after printing its value out, everything works fine again. list1 = [1, 2, 3] # create 2 lists list2 = ['A', 'B', 'C'] zipped = zip(list1, list2) # create zip object from the 2 lists: zipped print(list(zipped)) zipped = zip(list1, list2) # recreate zip object from the 2 lists: zipped test1, test2 = zip(*zipped) # unzip the zip using * print(list(test1)) print(list(test2))That's now the output I expected in the second code. I dont understand why I need to recreate my zip object to get the output I expected.
RE: zip() function does not work as expected - Gribouillis - Jan-31-2018 (Jan-31-2018, 04:47 PM)AyCaramba Wrote: Does the list(zipped) command in line 4 somehow destroy my zip object?The zip object is an iterable. The expression list(zipped) consumes the iterable. There are no more items in zipped after this expression.
|