randomesoldier
randomesoldier

Reputation: 7

too many values to unpack (expected 2) when using for loops

I keep on getting the error message : too many values to unpack (expected 2) when I tryout the below code :


sheetlist = [df1, df2, df3, df4, df5]

for i, j in sheetlist :
    j = i +1 
    final = i.merge(j, how = "outer", on = "columnname")


final.head()

May anyone know how to solve this?

Here's the complete Traceback

ValueError                                Traceback (most recent call last)

<ipython-input-54-981bc6246be4> in <module>()
      3 sheetlist = [df1, df2, df3, df4, df5]
      4 
----> 5 for i,j in sheetlist :
      6     j = i + 1
      7     final = i.merge(j, how = "outer", on = "columnname")

ValueError: too many values to unpack (expected 2)

Upvotes: 1

Views: 2130

Answers (2)

nir shahar
nir shahar

Reputation: 368

For starters, you need for i in sheetlist as @not_speshal said. In addition, notice that a for in python isn't unlike many other languages, and will enumerate the items inside the list, instead of the indices.

Hence, you might want something like this: for i in range(len(sheetlist)), and now i is indeed the valid index. To access the element at index i in the list, use sheetlist[i].

Upvotes: 0

coyote
coyote

Reputation: 304

The error is here :

for i, j in sheetlist :

The error appears because you are trying to unpack two values from a list, which is expecting to give one by one.

Upvotes: 1

Related Questions