Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7: Simple 'for' loop implementation

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."

like image 333
readytotaste Avatar asked Dec 19 '22 23:12

readytotaste


2 Answers

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!

like image 149
William T Froggard Avatar answered Jan 03 '23 17:01

William T Froggard


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.

like image 39
NPE Avatar answered Jan 03 '23 18:01

NPE