Python Forum

Full Version: for in loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
s = "ball"
r = ""
for item in s:
    r = item.upper() +  r
print(r)
Output will be LLAB, i.e print from the back.
Why is that so?
s = "ball"
r = ""
for item in s: # iterate over chars in s, i.e. value of item will change with each iteration of the loop
    print('item value -> {}'.format(item))
    r = item.upper() +  r # value of r will change, adding the value of item, upper case at the beginning of the old r value
    print('r value -> {}'.format(r))
print(r) # print the new value of r
I have added 2 print statements to show item and r values at each iteration.