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