Home > Software design >  Unpacking list in Python - ValueError: not enough values to unpack
Unpacking list in Python - ValueError: not enough values to unpack

Time:11-24

I test my script just printing return value of .split:

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    print(f_name.split('-'))

and it shows me what I'd like to see - lists with 3 strings in each.

['Earth ', ' Our Solar System ', ' #4']
['Saturn ', ' Our Solar System ', ' #7']
['The Sun ', ' Our Solar System ', ' #1']

However, when I'm trying to store it in 3 different variables:

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_title, f_course, f_num = f_name.split(' - ')

it gives me an error:

f_title, f_course, f_num = f_name.split('-')
    ^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 3, got 1)

I'd appreciate any help on this! Thanks!


CodePudding user response:

What you are experiencing is the diffrence between unpacking three items and a list. What you are getting from f.split is a single item only which is a list of the 'words'

f_name = 'a-b-c'
f_name.split("-") -> [a,b,c] #But a list is a single entity

So consider :

[title,course,num]= f_name.split("-")

However this is not a very good way to do it. What happens if split returns 4 words in a list ? Although this solves your problem, I highly doubt you should be doing it in this way.

CodePudding user response:

It seems like there are unwanted spaces around the hyphen f_name.split(' - '). Remove them:

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_title, f_course, f_num = f_name.split('-')
  • Related