0
lst = ['first', 'second']

for q,w in lst:
 print(q)
 print(w)

If I set my code like this, the result is an error. But if I do this way:

lst = [['first', 'second']]

  for q,w in lst:
    print(q)
    print(w)

The output is #first #second .

I don't understand the mechanism for this.. can somebody help me?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
gorang2
  • 49
  • 4

1 Answers1

2

A for loop is a form of an assignment statement. Each iteration assigns a new value to the target, and just like in a simple assignment statement, the target can be a sequence for tuple unpacking.

Your loop is equivalent to

for t in lst:
    q, w = t
    print(q)
    print(w)

The key difference is that in your first code, t is a string with more than 2 characters, so the unpacking fails. In the second code, t is a list with exactly 2 elements, so the unpacking succeeds.

chepner
  • 497,756
  • 71
  • 530
  • 681