I am new to programming and I was having some difficulty understanding the logic behind a Python 'for' loop implementation example I came across:
s="abcdefg"
t=""
for a in s:
t=a+t
I am confused as to why this piece of code returns "gfedcba." Why should it be any different from:
s="abcdefg"
t=""
for a in s:
t=t+a
... which returns "abcdefg."
Follow the logic like this:
s="abcdefg"
t=""
These are the starting variables, now lets "unroll" the for loop. Keep in mind that "a" stands for each character of "s", from first to last:
t = a + t
so t = "a"
t = a + t
so t = "ba"
t = a + t
so t = "cba"
Concatenation is not like addition. Order matters!
In effect, you are asking why a + t
and t + a
are not equivalent.
Here, +
denotes string concatenation rather than addition, and string concatenation is not commutative:
>>> "a" + "b"
'ab'
>>> "b" + "a"
'ba'
One way to think about your code is that
t = a + t
inserts a
at the front of t
, whereas
t = t + a
inserts it at the back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With