Unpacking a zip object causing ValueError

Viewed 512

I created a zip object using the following line of code:

k=zip([1,2,3],['a','b','c'])

Converting this into a list gives the output:

[(1,'a'),(2,'b'),(3,'c')]

However, when I use this line of code

x,y=zip(*k)

it gives me this ValueError:

"ValueError: not enough values to unpack (expected 2, got 0)"

I've been trying to find out what the problem is but couldn't figure anything out.

1 Answers

Method zip returns a iterator, so when you print it, you consume it so after that k is empty

  • apply the second zip directly

    k = zip([1,2,3],['a','b','c'])
    x,y = zip(*k)
    print(x, "/", y) # (1, 2, 3) / ('a', 'b', 'c')
    
  • wrap it in a list to use it multiple times

    k = list(zip([1,2,3],['a','b','c']))
    print(k)         # [(1, 'a'), (2, 'b'), (3, 'c')]
    x,y = zip(*k)
    print(x, "/", y) # (1, 2, 3) / ('a', 'b', 'c')
    
Related