Akhmad Zaki
Akhmad Zaki

Reputation: 433

Python For Loop (Iterating Variable Name = List Name)

I am running this Python code:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']

for numbers in numbers:
    print(numbers)
    for letters in letters:
       print(letters)

and got this output:

1
a
b
c
2
c
3
c

I do not understand why I got this output . What I am asking is what is the effect of using iterating variable with the same name with the sequence(list)?

Upvotes: 1

Views: 1702

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

  • why does it work the first time?

because for letters in letters: initialise the iteration on the name letters (which is a list of strings). Even if the letter variable is reassigned, the original list is already stored in the for iterator, so the loop runs properly

  • why it doesn't work / works so weirdly the next times?

After the first iteration, the name letters is no longer referencing your start list, but is referencing the last element of the original list, AKA c. Since strings are iterable, you don't get an error (like you would have gotten if letters were a list of integers, for instance), it just yields c over and over.

note that for letters in letters in itself makes no sense. The list of letters is properly named letters, but the variable name should be named letter, for instance, else it makes the code unclear.

Upvotes: 5

Related Questions