Home > Blockchain >  How to deal with unequal element list to unpack into multiple variables (ValueError: too many values
How to deal with unequal element list to unpack into multiple variables (ValueError: too many values

Time:04-06

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.

CodePudding user response:

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

CodePudding user response:

You can unpack a container into any number of variables, capturing whatever remains in a dummy variable like this:

a, b, c, *_ = [1, 2, 3, 4, 5, 6]

a    # 1
b    # 2
c    # 3
_    # [4, 5, 6]

The key is the * before the last variable (which could be given a name, as well).

  • Related