Thanks a lot!
what if i wanted to .pop() randomly…?
.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
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
Sorry, but this doesn’t make sense.
Link is irrelevant.
a += b will call
__iadd__ and mutate
a = a + b will create a new object and assign it to
This is not explaining why only 1st character assigned to students_in_poetry list.
That isn’t happening in that screenshot.
What are the first letters? What is printed? Doesn’t match.
>>> a += 18, 25 >>> a [2, 5, 9, 18, 25] >>>
The augmented value is a sequence. Likewise below,
>>> a = [2, 5, 9, 18, 25] >>> a += 'Python' >>> a [2, 5, 9, 18, 25, 'P', 'y', 't', 'h', 'o', 'n'] >>> a += ['Python'] >>> a [2, 5, 9, 18, 25, 'P', 'y', 't', 'h', 'o', 'n', 'Python'] >>>
this is great example!
But I’m still struggle to understand.
- string - it iterates
- list - treated as atomic entity
I can memorise like this, unless there is a better explanation.
+= iterates regardless. It doesn’t care in the slightest what the input is.
>>> a = [2, 5, 9, 18, 25] >>> a += 'Python' >>> a [2, 5, 9, 18, 25, 'P', 'y', 't', 'h', 'o', 'n'] >>> a += ['Python','Java'] >>> a [2, 5, 9, 18, 25, 'P', 'y', 't', 'h', 'o', 'n', 'Python', 'Java'] >>>
Thanks a lot for your help and support!