Django Training and Certification (3 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (48 Blogs)
  • Comprehensive Java Course (1 Blogs)
  • Java/J2EE and SOA (194 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

Python Remove List: How to remove element from Lists

Published on Jun 28,2019 200 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assement report and video recording

Python Programming Certification is one of the most sought after certifications in the market. The reason for this is the array of functionalities Python offers. Lists are one collection that simplifies the life of programmers to a great extent. In this article, we shall learn one such feature that is how to remove elements from lists.

Before moving on, let’s take a quick look at all that is covered in this article:

Why use Lists?
What are Lists?
Remove Elements from List using:

So let’s get started. :)

Why use Lists?

Sometimes, there may be situations where you need to handle different types of data at the same time. For example, let’s say, you need to have a string type element, an integer and a floating-point number in the same collection. Now, this is fairly impossible with the default data types that are available in other programming languages like C & C++. In simple words, if you define an array of type integer, you can only store integers in it. This is where Python has an advantage. With its list collection data type, we can store elements of different data types as a single ordered collection! 

Now that you know how important lists are, let’s move on to see what exactly are Lists and how to remove elements from list!

What are Lists?

Lists are ordered sequences that can hold a variety of object types. In other words, a list is a collection of elements which is ordered and changeable. Lists also allow duplicate members. We can compare lists in Python to arrays in other programming languages. But, there’s one major difference. Arrays contain elements of the same data types, whereas Python lists can contain items of different types. A single list may contain data types like strings, integers, floating point numbers etc. Lists support indexing and slicing, just like strings. Lists are also mutable, which means, they can be altered after creation. In addition to this, lists can be nested as well i.e. you could include a list within a list.  

The main reason why lists are an important tool in Python is because of the wide variety of the built-in functions it comes with. Lists are also very useful to implement stacks and queues in Python. All the elements in a list are enclosed within ‘square brackets’, and every element in it are separated by a ‘comma’.  

EXAMPLE:


myList = ["Bran",11,3.14,33,"Stark",22,33,11]

print(myList)

OUTPUT: [‘Bran’, 11, 3.14, 33, ‘Stark’, 22, 33, 11]


In the above example, we have defined a list called myList. As you can see, all the elements are enclosed within square brackets i.e. [ ] and each element is separated by a comma. This list is an ordered sequence that contains elements of different data types.  

At index 0, we have the string element ‘Bran’.

At index 1, we have an integer 11.

At index 2, we have a floating-point number 3.14.

In this way, we can store elements of different types in a single list.

Now that you have a clear idea about how you can actually create lists, let’s move on to see, how to Remove Elements from Lists in Python.

Remove Elements from a List:

There are three ways in which you can Remove elements from List:

  1. Using the remove() method
  2. Using the list object’s pop() method
  3. Using the del operator

Let’s look at these in detail.

List Object’s remove() method:

The remove() method is one of the most commonly used list object methods to remove an item or an element from the list. When you use this method, you will need to specify the particular item that is to be removed. Note that, if there are multiple occurrences of the item specified, then its first occurrence will be removed from the list.  We can consider this method as “removal by item’s value”. If the particular item to be removed is not found, then a ValueError is raised.

Consider the following examples:

EXAMPLE 1:


myList = ["Bran",11,22,33,"Stark",22,33,11]

myList.remove(22)

myList

 

OUTPUT: [‘Bran’, 11, 33, ‘Stark’, 22, 33, 11]

In this example, we are defining a list called ‘myList’. Note that, as discussed before, we are enclosing the list literal within square brackets. In Example 1, we are using the remove() method to remove the element 22 from myList. Hence, when printing the list using the print(), we can see that the element 22 has been removed from myList.

EXAMPLE 2:


 myList.remove(44)

 

OUTPUT:

Traceback (most recent call last):

   File “<stdin>”, line 1, in 

ValueError: list.remove(x): x not in list2

In Example 2, we use the remove() to remove the element 44. But, we know that the list ‘myList’ does not have the integer 44. As a result, a ‘ValueError’ is thrown by the Python interpreter.

(However, this is a slow technique, as it involves searching the item in the list.)

List Object’s pop() method:

The pop() method is another commonly used list object method. This method removes an item or an element from the list, and returns it. The difference between this method and the remove() method is that, we should specify the item to be removed in the remove() method. But, when using the pop(), we specify the index of the item as the argument, and hence, it pops out the item to be returned at the specified index. If the particular item to be removed is not found, then an IndexError is raised. 

 Consider the following examples: 

EXAMPLE 1:


 myList = ["Bran",11,22,33,"Stark",22,33,11]

 myList.pop(1)

Output: 11

In this example, we are defining a list called ‘myList. In Example 1, we are using the pop( ) method, while passing the argument ‘1’, which is nothing but the index position 1. As you can see from the output, the pop( ) removes the element, and returns it, which is the integer ‘11’.

EXAMPLE 2:


myList

OUTPUT[‘Bran’, 22, 33, ‘Stark’, 22, 33, 11]

Note that, in Example 2, when we print the list myList after calling pop(), the integer 11, which was previously present in myList has been removed.

EXAMPLE 3:


myList.pop(8)

OUTPUT:

Traceback (most recent call last):

   File “<stdin>”, line 1, in 

IndexError: pop index out of range

In Example 3, we use the pop() to remove the element which is at index position 8. Since there is no element at this position, the python interpreter throws an IndexError as shown in output.

(This is a fast technique, as it is pretty straightforward, and does not involve any searching of an item in the list.)

Python del operator:

This operator is similar to the List object’s pop() method with one important difference. The del operator removes the item or an element at the specified index location from the list, but the removed item is not returned, as it is with the pop() method. So essentially, this operator takes the item’s index to be removed as the argument and deletes the item at that index. The operator also supports removing a range of items in the list. Please note, this operator, just like the pop() method, raises an IndexError, when the index or the indices specified are out of range.

Consider the following examples:

EXAMPLE 1:


myList = ["Bran",11,22,33,"Stark",22,33,11]

del myList[2]

myList

OUTPUT: [‘Bran’, 11, 33, ‘Stark’, 22, 33, 11]

In the above example, we are defining a list called ‘myList. In Example 1, we use the del operator to delete the element at index position 2 in myList. Hence, when you print myList, the integer ‘22’ at index position 2 is removed, as seen in the output.

 

EXAMPLE 2:


del myList[1:4]

myList

OUTPUT:  [‘Bran’, 22, 33, 11]

In Example 2, we use the del operator to remove elements from a range of indices, i.e. from index position 1 till index position 4 (but not including 4). Subsequently, when you print myList, you can see the elements at index position 1,2 and 3 are removed. 

EXAMPLE 3:


del myList[7]

OUTPUT:

Traceback (most recent call last):

File “”, line 1, in 

IndexError: list assignment index out of range

In Example 3, when you use the del operator to remove an element at index position 7 (which does not exist), the python interpreter throws a ValueError.

(This technique of removing items is preferred when the user has a clear knowledge of the items in the list. Also, this is a fast method to remove items from a list.)

To summarize, the remove() method removes the first matching value, and not a specified index; the pop() method removes the item at a specified index, and returns it; and finally the del operator just deletes the item at a specified index ( or a range of indices). 

I hope you were able to go through this article and get a fair understanding of the various techniques to Remove Elements from List. 

Make sure you practice as much as possible and revert your experience.  

Got a question for us? Please mention it in the comments section of this “Remove Elements from List” blog and we will get back to you as soon as possible.

To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access. 

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.