+ 3
Can someone please explain
myList = [ 1, 2, 3] myList += 'hi' myList -> [ 1, 2, 3, 'h', 'i'] why does the string get split!!??
11 Answers
+ 5
Because strings are also an ordered sequence of values. It follows much of the same rules as lists, with exceptions of course. You can iterate a string, but not an integer for example.
When you ask python to:
mylist += "hello"
You're basically saying (add each character from this string). A string has indexing the same as lists.
So if you think of a string as a type of list where each character, space, symbol is treated as a value, it behaves the same as pythons [ ] lists. So the behavior is the same as adding two [ ] lists together.
mylist += ["hi"]
When you surrounded that string with a list, it did the same thing, only it treated the string inside that list as a value belonging to it.
Python can also handle other situations like if dictionaries or tuples were added the same way, that's more of a 'special case'. But python allows it. for convenience.
+ 2
the items that are 1 , 2 and 3 are integers. in this case I am trying to add a string to the list
+ 2
yeah, I thought that but I have just done another course and they are saying to you this method but with ['hi']
+ 2
can you please explain why it adds each character, one at a time??
+ 2
thank you for the fantastic reply
+ 2
the -> is a symbol that indicates what happens in the console!!
+ 1
python list object is capable of handling the expression you gave it, but it adds each string character one at a time.
To add to a list, it is better to just use the append method. This way it adds the value as a whole.
mylist.append("hi")
+ 1
Yes that works as well. By having the string encapsulated in a list will combine it with the list using the += expression.
mylist += ["hi"]
all that's happening is you're adding two lists together. That's essentially what is happening.
+ 1
not really an answer but added a string like my string saying 123 if you want to see it just check out my latest uploads
+ 1
I see but what happens if you print out the list
- 2
Is the array type char?