A post was split to a new topic: Why does this work the way it does?
Hi there,
I used list += item to add student in the poetry class, but they broke down as characters rather than original elements of a name. But when I used .append() it worked again. What’s the reason? Thanks a lot!
There is a really good stackoverflow question about it:
https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists
Oh great! Thank you and I’d spend some time to digest that~
yes, will take some time to digest. In any case, better use .append()
, given its a list specific method which won’t give this trouble.
Aside
A list can be concatenated with another list. It cannot, however, be concatenated with a single value that is not constructed as a list object.
>>> a = [2, 5, 9, 12]
>>> a += 18
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
a += 18
TypeError: 'int' object is not iterable
>>>
But, a sequence is iterable, so,
>>> a += 18, 25
>>> a
[2, 5, 9, 18, 25]
>>>
If we study the code in the screen-grab, we see a list being concatenated with a string (the popped object). The primitive cannot be concatenated; however, Python defines a string as iterable, and therefore assigns it as a sequence, hence they are inserted as single character string objects.
Edited: 2020/01/30
We can concatenate a single character string value; it’s a sequence with length 1.
I got it, and thanks again!
Great explanation!
Thanks a lot!
what if i wanted to .pop() randomly…?
Python’s .pop()
method supports indexing. When no index is given, the last element is popped, but when an index is given, it is that index to be popped.
With knowledge of the length of a list we can generate a random number (an index) that is within range.
from random import randrange
We import randrange
since it generates integers that will match (fall within) the range of our list.
names = ['Sasha', 'Eric', 'Maria', 'Jason', 'Alice',
'Mathew', 'Emma', 'Logan', 'Naomi', 'Parker']
n = len(names)
x = randrange(n)
print (names[x])
thanks a lot