0
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 ?

4
  • 2
    The + operation on lists is equivalent to extend, not append. Just as doing [1] + [2, 3] will result in [1, 2, 3] and not [1, [2,3]] Commented Feb 2, 2020 at 12:15
  • okay. This makes sense but in what scenario would we have to use extend() function when the + operator could do the same thing Commented Feb 2, 2020 at 12:34
  • A few reasons that are hard to list all here. Feel free to search for more details: extend is 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 Commented Feb 2, 2020 at 12:59
  • thank you. so much for the clarification Commented Feb 2, 2020 at 15:47

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

1 Comment

A better wording for list of characters would be a sequence. see here under the extend operation
0

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.