Can someone please explain | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can someone please explain

myList = [ 1, 2, 3] myList += 'hi' myList -> [ 1, 2, 3, 'h', 'i'] why does the string get split!!??

29th Jul 2017, 11:52 AM
Luke ward
Luke ward - avatar
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.
29th Jul 2017, 1:41 PM
Sapphire
+ 2
the items that are 1 , 2 and 3 are integers. in this case I am trying to add a string to the list
29th Jul 2017, 1:19 PM
Luke ward
Luke ward - avatar
+ 2
yeah, I thought that but I have just done another course and they are saying to you this method but with ['hi']
29th Jul 2017, 1:26 PM
Luke ward
Luke ward - avatar
+ 2
can you please explain why it adds each character, one at a time??
29th Jul 2017, 1:32 PM
Luke ward
Luke ward - avatar
+ 2
thank you for the fantastic reply
29th Jul 2017, 1:44 PM
Luke ward
Luke ward - avatar
+ 2
the -> is a symbol that indicates what happens in the console!!
2nd Aug 2017, 8:28 PM
Luke ward
Luke ward - avatar
+ 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")
29th Jul 2017, 1:23 PM
Sapphire
+ 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.
29th Jul 2017, 1:30 PM
Sapphire
+ 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
2nd Aug 2017, 6:34 PM
The Shift
The Shift - avatar
+ 1
I see but what happens if you print out the list
2nd Aug 2017, 6:55 PM
The Shift
The Shift - avatar
- 2
Is the array type char?
29th Jul 2017, 1:03 PM
josh mizzi
josh mizzi - avatar