I have the following function:
s = 'hello'
rev = ''
for char in s:
rev = char + rev
return rev
Why does the for loop above add the characters in reverse? I tried using rev += char and it returned the string in the original order, s. This was mentioned in a video and they didn't explain properly, just said "Python's for loop over string doesn't work that way". I want to know why it does this, so in the future I will be more inclined to avoid these mistakes.
Another question is, can I implement this type of line in the for-loop over lists and will it output the reverse of the list? Since lists are mutable.
rev = rev + charor simplyrev += char(which means the same thing) instead.return sdirectly.rev = ch + rev, that is: iterating over every character and adding it at the beginning ofrev.rev = "h" + ""sorevis set to"h". Then you haverev = "e" + "h"sorevis set to"eh"then you haverev = "l" + "eh"andrevbecomes"leh"and so on.'hello'[::-1]='olleh'. See Strings and Character Data in Python.['t', 'e', 's', 't'][::-1]=['t', 's', 'e', 't']lists too.