Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Adding and Removing List Elements

Resource linked in this lesson: Python’s Mutable vs Immutable Types: What’s the Difference?

00:00 In addition to what you’ve seen already, there’s still quite a few ways to add and remove list elements. To add one or more items to a list, you can use the append() method with the syntax my_list.append() passing in the item you want to add, the extend() method with the syntax my_list.extend() passing in an iterable of the multiple items you want to add, the insert() method with the syntax my_list.insert() passing in the index of the position where you want to add an item and the item you want to add.

00:31 Now how about removing elements? You can use the pop() method with the syntax my_list.pop() passing in an optional index location of the item you want to remove.

00:42 pop() also returns the item being removed from the list. And if you don’t pass an index, it will just remove the last element. The clear() method with the syntax my_list.clear(), which empties or clears the list.

00:55 The remove() method with the syntax, my_list. remove() passing in an item you want removed. remove() will search the list sequentially and it removes the first instance of item it encounters.

01:06 If the item is not found in the list, remove() will raise a ValueError. And similar to assignment, you can use the del keyword to delete by index or slice with the syntax del my_list[index] or del my_list[slice].

01:21 If you want to see these methods in action, follow me to the REPL.

01:26 First, make a list. Imagine you’ve opened a pet store and you’re using a list to track the pets you have for sale. pets = ["dog", "cat"].

01:37 Now to add to a list at a specific index, you can use insert(). Say you’ve added a dragon to your inventory and you want to give it top billing.

01:45 Call pets.insert() and pass in the integer 0 and the string "dragon", and the pet dragon has been inserted at the first position.

01:54 Something to note when you use insert(), whenever you insert to a list, the index of everything after the location of insertion needs to be shifted down.

02:03 So if all you really need is to add to a list, the most efficient way to do that is to add at the end. And for that, you can use the append() method.

02:10 You want to sell birds now, so you’re adding a phoenix to your inventory.

02:15 pets.append("phoenix") and there it is. A phoenix is now at the end of the list. But adding elements one at a time is kind of exhausting, right?

02:27 Can you add multiple elements like this? Perhaps a chimera and a manticore? Call pets.append() passing in the string "chimera" and the string "manticore".

02:37 Nope. You get a TypeError: list .append() takes exactly one argument. What if you pass them instead as a list? pets.append(["chimera", "manticore"]) as a list this time. It works, but if you look at pets, you’ll see that it’s probably not quite what you were expecting.

02:56 Now you have a list inside of a list instead of adding each of the elements separately. What you’ll want to do instead is use the extend() method. First, you can use the del keyword to delete the nested list.

03:08 It’s the last element, so use del pets[-1]. Confirm that the extra list is gone. And now use extend() passing in a list to add these two elements.

03:20 pets.extend(["chimera", "manticore"])

03:25 check pets. And yep, now the store is fully stocked. So what if you sell a pet? Say you sold the chimera and you need to remove it. You can use the remove() method.

03:36 Call pets.remove() and pass in the string "chimera". Take a look at pets and you see that it’s gone. But be careful not to sell a chimera you don’t have, because if you try to remove it again, pets.remove("chimera")

03:52 you will also get a ValueError: list .remove(x): x not in list. Watch out for that.

04:00 Okay, another example. Suppose the dragon got in a fight with the manticore and it’s injured and now it needs to go to the hospital. You’ll remove it from the list, but you still want to keep track of it.

04:10 When you need to retrieve and remove a list element, use the pop() method. Dragon is currently at index 0, so use the following:

04:19 in_hospital = pets. pop(0). See that the variable in_hospital holds the string "dragon" and the dragon has been removed from the list of pets.

04:31 Oh no, things are not looking good for business. The manticore escaped. Now go ahead and use pop() to remove it from the list. Call pets.pop() with no arguments.

04:42 By default, the last element is removed and returned. And in this case, you aren’t storing that string "manticore".

04:49 And finally, it seems your pet store has lost its business to operate as it’s actually illegal to trade in magical creatures. So use the clear() method to empty your inventory.

05:00 Call pets.clear() and examine pets. And the list is now empty. Don’t worry, everything left was rehomed and the dragon got better and the manticore became a vegetarian and everyone lived happily ever after.

05:15 Okay, that was a bit silly. But anyway, you now know a plethora of ways you can modify lists and these modifications are allowed because lists are mutable objects.

05:24 If you want to build an even deeper understanding of how Python handles mutability and immutability, I have the perfect recommendation for you: Python’s Mutable vs Immutable Types: What’s the Difference? And next up, we’ll look at ways you can combine existing lists.

Become a Member to join the conversation.