pythonpython-3.xvalueerrorlist-manipulation

Python3 ValueError - Too many values to unpack while iterating over a list


This is a simple code meant to generate a list of full names using a list of English first and surnames:

names = """
Walter
Dave
Albert""".split()

fullnames = [(first + last) for first, last in names]
print(fullnames)

I made names smaller just for the sake of this post, but I included 100 names.

output:

Traceback (most recent call last):
  File "/home/pussyslayer42069/Desktop/py/names.py", line 105, in <module>
    fullnames = [(first + last) for first, last in names]
  File "/home/pussyslayer42069/Desktop/py/names.py", line 105, in <listcomp>
    fullnames = [(first + last) for first, last in names]
ValueError: too many values to unpack (expected 2)

Solution

  • Use zip and iterate over two slices of the list

    [(f, l) for f, l in zip(names[:-1], names[1:]]