Which of the following can delete an element from a list if a index of the element is given?

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!

Remove an element from List by value using list.remove[]

Python’s list provides a member function to remove an element from list i.e.

list.remove[value]
It removes the first occurrence of given element from the list.

For example,

Suppose we have a list of numbers i.e.

# List of numbers listOfnum = [12, 44, 56, 45, 34, 3, 56, 4, 33, 44, 56]
Let’s remove 56 from the given list using list.remove[] i.e.
# Remove first occurrence of 56 from List listOfnum.remove[56]
It will remove the first occurrence of 56 from the above lists. Lists contents will be now,
[12, 44, 45, 34, 3, 56, 4, 33, 44, 56]
If we try to remove the element that doesn’t exists in list then list.remove[] will throw exception.
Therefore before calling list.remove[] we should either,

Advertisements

Check if element exists in list i.e.

# Check if element exist in List, before removing if 99 in listOfnum: listOfnum.remove[99] else: print["Given Element Not Found in List"]
Or use try / except i.e.
# If given element doesn't exists in list, then remove[] can throw Error # Therefore use try / except while calling list.remove[] try : listOfnum.remove[99] except ValueError: print["Given Element Not Found in List"]
Related Articles
  • Python: Remove elements from a list while iterating
  • Python: Remove elements from list by value [first or all occurrences]
  • Python: Remove elements from list by index or indices

Python: Remove an element from a list by index using the pop[] function

In Python, the list class provides a function pop[index] to remove an item from the list at the given index. But if the list is empty or the given index is out of range, then the pop[] function can raise IndexError. Therefore we should carefully use this function to delete an item from a list by index position.

We have created a function for deleting an element from a list by index. It internally uses the pop[] function but first checks if the given index is valid or not. Let’s understand by an example,

def delete_element[list_object, pos]: """Delete element from list at given index position [pos] """ if pos < len[list_object]: list_object.pop[pos] list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59] delete_element[list_of_num, 5] print[list_of_num]

Output:

Advertisements

[51, 52, 53, 54, 55, 57, 58, 59]

The function delete_element[] accepts two arguments,

  • A list, from where element needs to be deleted.
  • An index, that represents the position at which element needs to be deleted from the given list.

To avoid the IndexError by the pop[] function, delete_element[] first checks if the given index position is valid or not. If yes, then it deletes the element at the given index position by calling the pop[] function.

Let’s check out another example in which we are trying to delete an element by an index that is out of range,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59] delete_element[list_of_num, 15] print[list_of_num]

Output:

[51, 52, 53, 54, 55, 56, 57, 58, 59]

It did not affect the list because, in function delete_element[], it checked if the given index is valid or not.If we use pop[] function directly with this index, it will raise index error. For example,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59] list_of_num.pop[15]

Error:

list_of_num.pop[15] IndexError: pop index out of range

How to Delete Element in Python List

In python list, data structure consists of many built-in functions using which we can do several operations on the list elements. In this tutorial, we will learn how to delete the elements present in the list by the remove[], pop[], del method. The remove[]method removes the specified element from the list. If the specified element repeats in the list, it removes the first matching element. The pop[] method removes the element in the list. It returns the element present in the list. If no parameter is given, the pop[] method removes the last element present in the list. We can delete the particular element from the defined list by using the del keyword.

Example: Deleting elements from the list using the remove[] method.

The below example shows how to remove elements from the list using theremove[] method.

#Intializing list list_seq_1=[10,20,30,40,50,60] list_seq_2=[10,20,30,20,50,60] print["Elements present in the list before removing:",list_seq_1] # Removing elements from the list list_seq_1 list_seq_1.remove[50] print["Elements present in list after modifying are:",list_seq_1] print["Elements present in the list before removing:",list_seq_2] # Removing elements from the list list_seq_2 list_seq_2.remove[20] print["Elements present in list after modifying are:",list_seq_2]

In the above example, we define list_seq_1 with different elements and list_seq_2 with repeated elements. In the list_seq_1 we are trying to remove the element 50 from the list. The remove[] method searches the specified element in the list and removes the element from the list. In the list_seq_2 we are trying to remove the element 20 from the list. The element 20 is repeated two times in the list_seq_2. The remove[] method searches the specified element in the list and removes the first matching element in the list.

Once we run the program we will get the following result.


Elements present in the list before removing: [10, 20, 30, 40, 50, 60]
Elements present in list after modifying are: [10, 20, 30, 40, 60]
Elements present in the list before removing: [10, 20, 30, 20, 50, 60]
Elements present in list after modifying are: [10, 30, 20, 50, 60]

Example: Type Error.

The remove[] method takes one parameter. If we give more than one parameter or no parameters are given, we will get Type Error.

#Intializing list list_seq=[10,20,30,40,50,60] print["Elements present in the list before removing:",list_seq] list_seq.remove[] print["Elements present in list after modifying are:",list_seq]

Once we run the program we will get the following result.


Traceback [most recent call last]:
File "C:/PycharmProjects/pythonProject2/module_4.py", line 9, in
list_seq.remove[]
TypeError: remove[] takes exactly one argument [0 given]
Elements present in the list before removing: [10, 20, 30, 40, 50, 60]

Example: Value Error

We will get ValueError, if the remove method failed to search the specified element.

#Intializing list list_seq_1=[10,20,30,40,50,60] print["Elements present in the list before removing:",list_seq_1] list_seq_1.remove[80] print["Elements present in list after modifying are:",list_seq_1]

In the above example, we are trying to remove the element from the list list_seq_1. But the specified element is not present in that list.

Once we run the program, it shows the below result.


Traceback [most recent call last]:
File "C:/PycharmProjects/pythonProject2/module_4.py", line 10, in
list_seq_1.remove[80]
ValueError: list.remove[x]: x not in list
Elements present in the list before removing: [10, 20, 30, 40, 50, 60]

Example: Deleting elements from the list using pop[] method with and without parameter.

The below example shows how to remove elements from the list using the pop[] method.

#Intializing list list_seq_1=[10,20,30,40,50,60] print["Elements present in the list before removing are:",list_seq_1] list_seq_1.pop[2] print["Elements present in list after removing are:",list_seq_1] list_seq_1.pop[] print["Elements present in list after removing are:",list_seq_1]

In the above example, we are using the pop[] method to remove the element in the list. First, we are trying to remove the element by giving an index value. The pop[] method removes the element present in the specified index. Next, we are trying to remove the element. But there is no parameter given, the pop[] method removes the last element in the list.

Once we run the program, it shows the below result.


Elements present in the list before removing are: [10, 20, 30, 40, 50, 60]
Elements present in list after removing are: [10, 20, 40, 50, 60]
Elements present in list after removing are: [10, 20, 40, 50]

Example: Index Error

The pop[] method raises IndexError when it fails to find the specified index.

#Intializing list list_seq_1=[10,20,30,40,50,60] print["Elements present in the list before removing are:",list_seq_1] list_seq_1.pop[9] print["Elements present in list after removing are:",list_seq_1]

In the above program, we gave the index number 9 which is out of range.

Once we run the program, it shows the below result.


Traceback [most recent call last]:
File "C:/PycharmProjects/pythonProject2/module_4.py", line 9, in
list_seq_1.pop[9]
IndexError: pop index out of range
Elements present in the list before removing are: [10, 20, 30, 40, 50, 60]

Example: Deleting elements from the list using del keyword.

The below example shows how to delete a particular element from the list by using the del keyword.

We can give a negative index also.

#Intializing list list_seq_1=[10,20,30,40,50,60] print["Elements present in the list before removing are:",list_seq_1] del list_seq_1[1] print["Elements present in list after removing are:",list_seq_1] del list_seq_1[-1] print["Elements present in list after removing are:",list_seq_1]

In the above example, we are trying to delete the elements from the list using the del keyword. First, we gave a positive index value. The del keyword removes the element which is present in the index value 1. i.e Element 20. Next, we gave a negative index value. The del keyword removes the element which is present in the index value 1. i.e Element 60.

Once we run the program, it shows the following result.


Elements present in the list before removing are: [10, 20, 30, 40, 50, 60]
Elements present in list after removing are: [10, 30, 40, 50, 60]
Elements present in list after removing are: [10, 30, 40, 50]

Conclusion:

In this tutorial, we learned how to delete elements in the list using the built-in functions of the list. We solved examples and delete the elements present in the list using the remove[] method, pop[] method, and del keyword.

Remove an item from a list in Python [clear, pop, remove, del]

Posted: 2019-05-29 / Modified: 2021-04-06 / Tags: Python, List

Tweet

In Python, use list methods clear[], pop[], and remove[] to remove items [elements] from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

  • Remove all items: clear[]
  • Remove an item by index and get its value: pop[]
  • Remove an item by value: remove[]
  • Remove items by index or slice: del
  • Remove items that meet the condition: List comprehensions

See the following article for adding items to the list.

  • Add an item to a list in Python [append, extend, insert]

Sponsored Link

Video liên quan

Bài mới nhất

Chủ Đề