1

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)?

6
  • 2
    Think of the loop as setting letters = 'a', letters = 'b', letters = 'c' the first time. The next time, it’s just looping over 'c'. Commented Jan 10, 2018 at 18:15
  • for letters in letters is the culprit. change your loop variable name, specially in an inner loop (or reset letters inside the outer loop). Anyway, it should be for letter in letters. Commented Jan 10, 2018 at 18:15
  • Once you are done with the first iteration of the outer loop, i.e., when the inner loop has done a full cycle, letters == 'c'. So on the second iteration for letters in letters: you are iterating over the string "c' Commented Jan 10, 2018 at 18:18
  • This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting. Commented Jan 10, 2018 at 18:19
  • 2
    @cᴏʟᴅsᴘᴇᴇᴅ on the contrary, I think OP is aware of the identical variable names: "(Iterating Variable Name = List Name)" quoting from title of the question. Commented Jan 10, 2018 at 18:21

1 Answer 1

5
  • 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.