ValueError: too many values to unpack (expected 3) in Python

Dung Do Tien Aug 14 2021 174

Hello Guys, I'm a newbie in Python and now I have an array with days of weeks as below:

week_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
mon, tue, wed = week_days
print(mon)
print(tue)
print(wed)

I want to assign value items to variables but I don't want to loop file. But I got an error ValueError: too many values to unpack (expected 3)

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    mon, tue, wed = week_days
ValueError: too many values to unpack (expected 3)

How can I get only three first items into three variables?

Have 2 answer(s) found.
  • J

    Jose Luis Aug 14 2021

    You can list all variables equal with items of an array. You can see the example below:

    week_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    mon, tue, wed, thur, fri, sta, sun = week_days
    print(mon)
    print(tue)
    print(wed)
    
  • D

    Dũng Đô La Aug 14 2021

    You can use * start symbol for variable fourth to end of the array. 

    week_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    mon, tue, wed, *thur = week_days
    print(mon) # output Monday
    print(tue) # output Tuesday
    print(wed) # output Wednesday

    I hope it helpful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close