Jan-31-2018, 04:47 PM
This is my code for creating 2 lists, zipping them together, unzipping them and printout the unzipped lists.
When I recreate zipped in line 5, after printing its value out, everything works fine again.
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:
Output:[1, 2, 3]
['A', 'B', 'C']
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:
Error:line 5, in <module>
test1, test2 = zip(*zipped) # unzip the zip using *
ValueError: not enough values to unpack (expected 2, got 0)
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.
Output:[(1, 'A'), (2, 'B'), (3, 'C')]
[1, 2, 3]
['A', 'B', 'C']
I dont understand why I need to recreate my zip object to get the output I expected.