简体   繁体   中英

Applying arithmetic operators to list elements in python

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 ?

The += operator for lists doesn't append an element to a list, it concatenates two lists. for example:

a = [1, 2, 3]
b = [2, 3, 4]
>>> a += b # will give you [1, 2, 3, 2, 3, 4]

Now, if we try to use + operator for appending an element it will throw an exception

>>> a += 2
TypeError: 'int' object is not iterable

Now let's come to your case. The string is interpreted as a list of characters, that's why the operation you try to do is viewed as concatenating a list with a list of chars.

>>> a = [] 
>>> a += "hello"
>>> a

['h', 'e', 'l', 'l', 'o']

Actually no, the actual output is fine, this is why.

when you try to add "hi" to ['hi', 'how', 'are', 'you'], you are trying to add a string to a list of strings. This should be an error. But actually strings are already a list of characters. What you are doing is that you are effectively adding lists to lists, hence ['hi', 'how', 'are', 'you'] get combined with each letter in "Hi"

What you want to do can either be achieved by s.append(s[i]) or by s += [s[i]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM