Exercise 38: Doing things to Lists

I noticed something today that I wanted to share with the group. Since I have a feeling that lists (aka, data structures) are going to be a huge topic going forward (and are used all over the place in real-world applications), I’ve been spending some additional time on it to get the concepts nailed down.

For all the exercises in the book, I typically like to type in Zed’s code and then try to solve it (by typing the output) in another text file, before looking at the “What you Should See” results.

For this exercise, I got it all wrong, mostly because I forgot how pop() works.

Let’s say I have the following list that holds the following 6 months:

months = [“january”, “february”, “march”, “april”, “may”, “june”]

Now, let’s say I want to see what happens when I “pop” off a month using pop():

print(months.pop())

I wrongly assumed that the pop’d value would be “january”, since it’s the first item in the list. Nope. It’s “june”. I observed that if no value is put in the (), then Python returns the last item in the list.

Even further, I found through testing that each of the three (null, 5, and -1) following pop values also pop “june” from the above months list:

print(months.pop())
print(months.pop(5))
print(months.pop(-1))

Are my assumptions correct? Sorry if this is overly basic for a lot of you, but it was fairly revelatory for me on how python looks at, reads, and performs an action on a list.

1 Like

yes, pop() removes the last item.
So the last item in that particular list is june, which is also the fifth index, and the -1 index.

I believe remove(item) will only remove the first item, reading from 0 index => end of list. So pop is going from last item => 0.

Theres a really good thread on the differences here:

Now I’m curious if a method exists to remove all of a particular value from a list, but I imagine an iteration error would happen. The list would change lengths as the items are removed. That is probably why you can only remove one at a time.

Good stuff @latechwriter.

2 Likes