3

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.

azro
  • 53,056
  • 7
  • 34
  • 70
  • it's working for me. did you get the error with same example you posted – deadshot Jun 01 '20 at 17:47
  • 4
    You can't consume the iterator twice. – user2357112 Jun 01 '20 at 17:48
  • There must be something else wrong with your code. I converted your problem into a one-liner and that works fine. Please run the one-liner and confirm whether it works for you or not: `zip(*list(zip([1,2,3],['a','b','c'])))` – Cerno Jun 01 '20 at 17:49
  • Yes I did @komatiraju032. – random math student Jun 01 '20 at 17:50
  • Please take a look at your list conversion. You seem to apply zip(*) to k, which is not the list, but the original result of zip(). If you convert it to a list it will become a copy, so you will have to unzip your list, not k. – Cerno Jun 01 '20 at 17:52
  • This works for me, apparently it also works if I use the line right after creating the zip object, but not if I use it for something else before that. As the comment before yours points out @Cerno. Yep your second comment also seems to work. Thanks! – random math student Jun 01 '20 at 17:53
  • Can you post a full running example that raises the error? The error suggests that you are using the iterator twice - its empty the second time - but we are only guessing until you post it. BTW, try `list(k)` twice and you'll see the problem. – tdelaney Jun 01 '20 at 18:13

1 Answers1

4

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')
    
azro
  • 53,056
  • 7
  • 34
  • 70