0

I started learning Python, and I'm working on input/output subject and I got this error:

  File "c:\Users\never\Desktop\Projects with IT\__pycache__\writing.py", line 30, in <module>
    title, artist, year, tracks = imelda
ValueError: too many values to unpack (expected 4)

And this is my code:

imelda = ('mother may', 'Imelda May', '2011', (1, 'Pulling the Rug'), (2, 'Psycho'), (3, 'Amine'))
print(imelda)

title, artist, year, tracks = imelda
print(title)
print(artist)
print(year)   
mkrieger1
  • 14,486
  • 4
  • 43
  • 54
Ruth Davis
  • 11
  • 3
  • The error means that you specified more values to unpack than the code you evaled returned. print(imelda) and see how many values does it have – Marat Mkhitaryan Feb 11 '21 at 01:46
  • 1
    Did you count the number of items in the tuple? There are more than 4. – mkrieger1 Feb 11 '21 at 02:04
  • This should answer your question: [Head and tail in one line](https://stackoverflow.com/questions/10532473/head-and-tail-in-one-line) - use `title, artist, year, *tracks = imelda`. – mkrieger1 Feb 11 '21 at 02:12

3 Answers3

0

The reason why you have this error is because what you would consider to be tracks is in fact not a list but 3 seperate parameters:

('mother may', 'Imelda May', '2011', (1, 'Pulling the Rug'), (2, 'Psycho'),(3, 'Amine'))

If your data is structured like this:

('mother may', 'Imelda May', '2011', ((1, 'Pulling the Rug'), (2, 'Psycho'),(3, 'Amine')))

It will have no issues. (Note the extra parentheses around the track objects.)

VBence
  • 21
  • 3
0

The text file contains 6 values while you want to unpack the values in 4 variables. The solution:

with open("a.txt", 'r') as imelda_file:
    contents = imelda_file.readline()

imelda = eval(contents)

# Notice the * before tracks. It unpacks all the remaining values into tracks in the form of a tuple
title, artist, year, *tracks = imelda
reddragonnm
  • 16
  • 1
  • 2
0

You can use a catch-all placeholder while unpacking. See example behavior below.

title, artist, year, *tracks = imelda

>>> a = [1,2,3,4,5,6,7]
>>> b,c,*d = a
>>> b
1
>>> c
2
>>> d
[3, 4, 5, 6, 7]
>>> 

This again means that your file satisfies at least three values per line rule.

lllrnr101
  • 2,123
  • 2
  • 3
  • 14