How to fix ValueError: not enough values to unpack (expected 3, got 1) in Python?

Viewed 6741

I have a dataset called records, a dataset sample looks like:

first_record = records[0]
print(first_record)
_____________________________
['1', '1001', 'Movie']

I would like to extract each value for further computation, and when I do the following code:

for user, item, tag in first_record :
    print(user, item, tag)

I am having this error:

----> 1 for user, item, tag in first_record :
      2     print(user, item, tag)

ValueError: not enough values to unpack (expected 3, got 1)

How can I extract each value corresponding to my user, item, tag variables in the dataset?

3 Answers

It looks like you meant to iterate over records, not first_record (the first element in the records list), and for each record print those three values:

for user, item, tag in records:
    print(user, item, tag)

if first_record only has these 3 elements you can directly assign variable as follows:

first_record = ['1', '1001', 'Movie']                                                                               
user,item,tag = first_record                                                   
print (user,item,tag)

You're trying to iterate over 1D list, hence the problem. You can convert it into a 2D list like so

first_record = [records[0]]

Then you should be able to iterate

for user, item, tag in first_record :
    print(user, item, tag)

EDIT: As pointed out in the comment, if you're using just record[0] then it's best not to iterate, rather assign the values directly like so

user, item, tag = first_record
print(user, item, tag)
Related