Search code examples
pythoniterable-unpacking

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


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?


Solution

  • 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)