Python Fundamentals

Removing Items from a List

Python Fundamentals

Check out a free preview of the full Python Fundamentals course

The "Removing Items from a List" Lesson is part of the full, Python Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Nina introduces the remove, pop, and push

Preview
Close

Transcript from the "Removing Items from a List" Lesson

[00:00:01]
>> Nina Zakharenko: Okay, there are a few ways of removing items from the list. Be a little bit careful with the remove method because just like insert it only removes the first one. So if I have a list of names, Nina and Max. And I call names.remove. On max. I'm just going to have a names list with one item in it.

[00:00:31]
But if my names list has a duplicate value in it, and I call names.remove Nina. Gonna see that it only removed that first instance of Nina and not the last one.
>> Nina Zakharenko: If we try to remove something from the list that's not there,
>> Nina Zakharenko: What am I gonna see?

[00:01:02]
I mean it's going to be an error, but which one?
>> Student: Hex index not found or something.
>> Nina Zakharenko: It's a value error. Yeah. Hex is not in list. You can use the pop method to remove the last item. Or you can use my list of pop with an index to remove an item at a particular position.

[00:01:32]
The nice thing about pop is that it will also return the item that was just removed in case you wanna do anything with it, or save it or anything like that. So if I call names.pop, what will my names list look like? Max, right? And what will names.pop return?

[00:01:54]
>> Student2: Nina.
>> Nina Zakharenko: Yeah, yep, exactly right
>> Nina Zakharenko: Making a new slightly longer list of names.
>> Nina Zakharenko: I can call names.pop and give this function an index. So I'm gonna pop 1, it's gonna pop the value Rose and remove it from the list.
>> Nina Zakharenko: So now the length of names is 2, right?

[00:02:35]
What happens if I try to pop the item, at index two?
>> Student: Index error.
>> Nina Zakharenko: Index error. Pop index out of range.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now