string="hi how are you"
s =string.split()
print(s)
for i in range(len(s)):
print(s[i])
s += s[i]
print(s)
I just began learning python and I noticed something weird which didn't make sense to me.
So when I do s += s[i] shouldn't I be getting something like this
['hi', 'how', 'are', 'you', 'hi', 'how', 'are', 'you']
but instead I'm getting something like this: ['hi', 'how', 'are', 'you', 'h', 'i', 'h', 'o', 'w', 'a', 'r', 'e', 'y', 'o', 'u'].
why do the individual letters get added?
I know we can obtain this ['hi', 'how', 'are', 'you', 'hi', 'how', 'are', 'you'] using the append function but isn't + supposed to do the same thing ?
+operation on lists is equivalent toextend, notappend. Just as doing[1] + [2, 3]will result in[1, 2, 3]and not[1, [2,3]]extendis an instance method that work on a list in-place and does not return a new list; handles with type mismatch better, for example:[1,2] +"34"raises an error while[1,2].extend("34")works just fine