FAQ: Learn Python: Loops - While Loops

Great explanation!
Thanks a lot!

1 Like

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 :slight_smile:

1 Like

Fine

fine

fine

Sorry, but this doesn’t make sense.

Link is irrelevant.
They discussing
a += b will call __iadd__ and mutate a ,
whereas a = a + b will create a new object and assign it to a

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.

Consider,

>>> 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']
>>> 
1 Like

this is great example!
But I’m still struggle to understand.

So for

  1. string - it iterates
  2. list - treated as atomic entity

I can memorise like this, unless there is a better explanation.

1 Like

list’s += iterates regardless. It doesn’t care in the slightest what the input is.

1 Like

Make sense!!!


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