Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking a zip object causing ValueError

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.

like image 782
random math student Avatar asked Aug 26 '26 02:08

random math student


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')
    
like image 156
azro Avatar answered Aug 27 '26 16:08

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!