Remove a Few Things


#1



https://www.codecademy.com/en/courses/python-beginner-en-pwmb1/2/4?curriculum_id=4f89dab3d788890003000096

If I have a list:

beatles = ["john", "paul", "george", "ringo", "stuart"]

I know from the exercise that
beatles.remove("stuart")
will remove the first item from the beatles list that matches str "stuart"

However, what if I had more than one "stuart" in that list? How would I go about deleting ALL the "stuart" strings not just the first one it encounters?

Hope that makes sense.
Thank you all in advance!


#2

this is surprisingly more difficult then you would expect.

the best approach would be to use the built in filter() function:

filter(lambda a: a != "stuart", beatles)

but as you can see, this is quit complex.

if we just make a loop, and use remove() everytime we see a "stuart" won't work, given if the 2 stuarts in a row, the second one would be skipped (index shift), so then we would need to loop over the list in reverse (or a copy of the list)


#3

Thanks for the reply! I had to look a little more into the filter() function and lambda but now that I've got a grasp on that - makes sense. :smiley:

Part of me is a tad curious as to how you would even loop a list in reverse or copy a list though? Just for curiosity's sake. But, I understand that may be a whole other complex thing in itself.

Again, thanks for taking the time to reply. Learning about lambda opened up a lot of possibilities for me.


#4

filter will be covered later in this course as well.

well, we have a reversed() built in function in python:

for beatle in reversed(beatles):
  if beatle == "stuart":
       beatles.remove("stuart")

as for the copy of the list, there are couple of tricks we can use, list slicing:

for beatle in beatles[:]:

or the built in list() function:

for beatle in list(beatles):

but i think this solutions are all less efficient.

a little googling also reminded we can simply make a new list:

new_beatles = []
for beatle in beatles:
    if beatle != "stuart":
        new_beatles.append(beatle)

which we can shorten using a list comprehension:

new_beatles = [beatle for beatle in beatles if beatle != "stuart"]

which also will be covered later. Pretty cool, right? :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.