FAQ: Learn Python: Loops - While Loops

A post was split to a new topic: Why does this work the way it does?

2 posts were split to a new topic: Where is the typo in my code?

2 posts were split to a new topic: Should we print inside of the loop?

2 posts were split to a new topic: What is the purpose of index +=1?

2 posts were merged into an existing topic: How does .pop() work?

2 posts were split to a new topic: Why do I get an index error?

7 posts were merged into an existing topic: How does .pop() work?

3 posts were split to a new topic: Why does the code use less than 6 if it needs to stop at 6?

2 posts were split to a new topic: Why does my list stop at 5?

2 posts were split to a new topic: How can I use random to generate names?

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.

1 Like

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.

3 Likes

I got it, and thanks again!

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