-2

I'm trying to print two variables with a for loop from two different lists with an equal amount of values, but when the lists have more than two values I get this error:

ValueError: too many values to unpack (expected 2)

Assume both name and surname lists are the same length (eg. name = ['m', 'y', '.', '.'] and surname = ['n', 'a', 'm', 'e'])

for x,y in name,surname:
    print(x,y)

My expected result is "my.." and "name" printed next to each other vertically.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • 1
    Your `for` loop is iterating over a sequence with a length of two: `name` followed by `surname`. Each of those two items gets unpacked into `x` and `y`, which fails because they contain four elements each. To iterate the two sequences in parallel, use `zip(name, surname)`. – jasonharper Dec 25 '18 at 15:16
  • Go through [this](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) post. Everything is in detail – Sheldore Dec 25 '18 at 15:50

1 Answers1

1

Use zip():

name = ['m', 'y', '.', '.']

surname = ['n', 'a', 'm', 'e']

for x, y in zip(name, surname):
    print(x, y)

Result:

m n
y a
. m
. e
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160