Reputation: 29
Here I'm trying to make a sub-list from list, and I'm getting "Not enough values to unpack error.
If I use k=s.split(',')
it shows the error, whereas if I use k1=[s.split(',')]
, it doesn't show any error while unpacking.
Both have the same type, same size and same-content
My code:
inputs = ["1, foo, bar", "2, tom, jerry"]
outputs1=[]
for s in inputs:
print(s)
k=s.split(',')
print(k,type(k),len(k))
k1=[s.split(',')]
print(k1,type(k1),len(k1))
for (x, y, z) in k:
outputs1.append([int(x), y.strip(), z.strip()])
print(outputs1)
Upvotes: 0
Views: 2404
Reputation: 82949
Using k
, you have a tuple with three elements, and in for (x, y, z) in k
you try to unpack each of those three elements to three more element. This does not work. Using k1
, you have a list with a single three-elemented tuple inside. Here, for (x, y, z) in k1
would work, but it's entirely pointless.
Instead, you should unpack the values directly to x, y, z
:
for s in inputs:
x, y, z = s.split(',')
outputs1.append([int(x), y.strip(), z.strip()])
Upvotes: 2
Reputation: 4638
Try this:
inputs = ["1, foo, bar", "2, tom, jerry"]
outputs1=[]
for s in inputs:
print(s)
k=s.split(',')
print(k,type(k),len(k))
k1=[s.split(',')]
print(k1,type(k1),len(k1))
for (x, y, z) in k1:
outputs1.append([int(x), y.strip(), z.strip()])
print(outputs1)**
Outputs1:
[[1, 'foo', 'bar'], [2, 'tom', 'jerry']]
I'm just fixing your code but there is much better way to write this code
Upvotes: 0
Reputation: 722
k = s.split(',')
this is where the error occours.
s.split(',')
in your case returns 3 strings. Buy on the left hand side theres only one variable k. You cannot assign 3 variables to only one variable.
changing it to
k1, k2, k3 = s.split(',')
will work
Upvotes: 0
Reputation: 17269
You need for (x, y, z) in k1:
instead of for (x, y, z) in k:
.
Upvotes: -1