Pages

Monday, January 9, 2023

Removing elements from a list in Python with list method pop()

Removing elements from a list

It's often essential to remove the data from any data set (let's take 'list' in this case). 

The list method "pop()" comes handy in this case, this method allows removing the last element of a list and return the same. This is a very useful method for amending lists by removing it's elements and can be used in a variety of situations as required.

Using "pop()" to remove the last element from a list

By default "pop()" method removes the last element from a list and returns the same. 

One thing to note here is, it modifies the original list. 

1

2

3

4

5

numbers = [1, 2, 3, 4]

removed_element = numbers.pop()

print(removed_element) # 4

print(numbers) # [1, 2, 3]

 


In the above example, 
  • pop() method removes the last element (i.e., "4" in this case) from the list "numbers". 
  • Returns the removed element, in this case returned element is stored in "removed_element". 
  • Original list is modified to only contain the remaining elements. 
One thing to note here is, if we try to remove the elements from an empty list, it'll raise an IndexError.

1

2

3

4

5

numbers = []

removed_element = numbers.pop() # throws error

print(removed_element)

print(numbers)

 


When we run the above code to remove an element from empty list, an error would be throws (see below). 

Traceback (most recent call last):

  File "C:\Users\pradeep.panga\PycharmProjects\pythonProject\pop.py", line 2, in <module>

    removed_element = numbers.pop()

                      ^^^^^^^^^^^^^

IndexError: pop from empty list


It is important to handle such errors when working with "pop()" method to avoid program failure run time. 

This can be done in one of the two ways. 
  • By checking if the list is empty before calling the pop() method. 
  • By using the pop() method inside try-except block and monitor for the IndexError. 

Removing elements from specific positions in a list

When working with data, we do not always want to remove a last element from list. We often need to remove a specific element from the beginning or middle of a list. 

"pop()" can also be used to remove the element from any position. To achieve this, we would need to pass the index position of the element which needs to be removed.

1

2

3

4

5

numbers = [1, 2, 3, 4]

removed_element = numbers.pop(2)

print(removed_element) # 3

print(numbers) # [1, 2, 4]

 


In the above example, 
  • "pop(2)" removed the element "3" from index position "2". 
  • Original list has been amended to remove the corresponding element from the list. 

Using pop() in a loop to remove all elements from a list

In the previous examples, we have seen how to delete a single element from a list. 

We could use the "pop()" method in a while loop to remove all the elements from a list. 

E.g.: 
Removing all elements from a list by using pop() in a while loop. 

1

2

3

4

5

6

7

8

9

numbers = [1, 2, 3, 4]

removed_elements_list = []

while numbers:

   removed_element = numbers.pop()

   removed_elements_list.append(removed_element)

 

print(numbers) # []

print(removed_elements_list) # [4, 3, 2, 1]

 


In the above example, 
  • Line - 3: "while numbers:" - This loop is repeated until the list is empty. So, loop will not run on a empty list and IndexError will not occur. 
  • Lines - 4 & 5: Last element from the list is removed and added to the new list created (i.e., removed_elements_list).
  • Line - 7: Original list (i., numbers) is empty as all the elements were removed. 
  • Line - 8: New list (i.e., removed_elements_list) contain the elements in reverse order to the original list as the elements are removed from the last index and added. 
Using a while loop and pop() method to remove all elements from a list can be an effective approach, especially if the list is large. It avoids the need to create a new list, which can be slower and requires allocation of further system resources.

One thing to remember here is, This would only work if we do not require the original list as the pop() methods removed the element and by the end of the loop, original list would be empty. 

We could also keep a copy of the list if required, before starting to use the pop() method.

Conclusion

In this post, we explored the usage of a list method "pop()" and how to remove the element from the end of a list, any index position of a list and to remove all the elements by using pop() in a loop. 

Hope this has been a bit of help in understanding the use of list method pop() in Python.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

No comments:

Post a Comment

Removing elements from a list in Python with list method pop()

Removing elements from a list It's often essential to remove the data from any data set (let's take 'list' in this case).  T...