0

I dont see why this code produces '11', how does the char work as iterable "i" index and value at the same time?

chars = "1234"
char = ""
for char in reversed(chars):
    char += char

print(char)
Random Davis
  • 6,662
  • 4
  • 14
  • 24
ERJAN
  • 23,696
  • 23
  • 72
  • 146
  • 1
    I suggest stepping through this code line-by-line in a debugger, on paper, or in your head, to determine what's happening at each step. – Random Davis Mar 03 '22 at 18:47
  • In the last iteration, `char` is initally `'1'`. Then you reassign `char` to `char + char`, giving you `'11'`. Then you print this value. – timgeb Mar 03 '22 at 18:48
  • The `for` loop resets `char` each iteration. Thus only the final iteration of the loop is meaningful and that takes `"1"` and appends `"1"` to it resulting in `"11"` – JonSG Mar 03 '22 at 18:51
  • In each iteration, the for loop is replacing the value of char, so in the last iteration, char is '1' and that's because you get '11' – Clovis Ignacio Ferreira Mar 03 '22 at 18:51

1 Answers1

1

Let's break down what's happening, step by step.

First, the setup:

chars = "1234"
char = ""

Now, the loop starts:

for char in reversed(chars)
# equivalent to: for char in reversed("1234")
# equivalent to: for char in "4321":

So now, because we put the variable char in the for loop, the value of char is going to be overwritten on each loop iteration, equivalent to:

char = "4"

Now, we're adding it to itself, which will result in the character doubled:

char += char
# equivalent to: "4" + "4"
# which equals "44"
# therefore:
char = "44"

Now for the next iteration, because we have char in the for loop, its value is now assigned to the next item in the list (thus clearing out its previous value):

char = "3"

Then we just continue on:

char += char
"3" + "3" = "33"
char = "2"
char += char
"2" + "2" = "22"
char = "1"
char += char
"1" + "1" = "11"

Now, the loop is over, so we move past it

print(char)
# equivalent to print("11")

output:

11
Random Davis
  • 6,662
  • 4
  • 14
  • 24