Search code examples
pythonlistvalueerror

How to deal with unequal element list to unpack into multiple variables (ValueError: too many values to unpack (expected 4))


I want to extract data from my dataset, but I found out that the list contain nested list with unequal element length inside.

My code that get unpacked value from list

obtainedDatetime, itemName, itemType, itemRarity, bannerCode, obtainedTimestamp = item

Dataset that contains 4 elements.

[
  "2021-04-20 04:19:22",
  "Skyrider Sword",
  "Weapon",
  3
]

Dataset that contains 6 elements (but I want only first 4 elements)

[
  "2022-01-10 16:26:53",
  "Bloodtainted Greatsword",
  "Weapon",
  3,
  "301",
  "1641801960000166133"
]

If the list contains 6 element, Python will raise an error.

ValueError: too many values to unpack (expected 4)

When I set the variable to get the unpacked value to 6, I recieved an error.

ValueError: not enough values to unpack (expected 6, got 4)

How to handle the unequal element in the nested list.


Solution

  • Use extended iterable unpacking features:

    obtainedDatetime, itemName, itemType, itemRarity, bannerCode, obtainedTimestamp, *rest = item
    

    So, rest will contain a list with the rest of the iterable. If you are not interested in this data, conventionally, we would name it _. So:

    obtainedDatetime, itemName, itemType, itemRarity, bannerCode, obtainedTimestamp, *_ = item