Which method is used to delete elements from a list if index is not known

Python remove() method

Python removes () method is a built-in method available with the list. It helps to remove the given very first element matching from the list.

Syntax:

list.remove(element)

The element that you want to remove from the list.

ReturnValue

There is no return value for this method.

Tips for using remove() method:

Following are the important points to remember when using remove () method:

  • When the list has duplicate elements, the very first element that matches the given element will be removed from the list.
  • If the given element is not present in the list, it will throw an error saying the element is not in the list.
  • The remove () method does not return any value.
  • The remove () takes the value as an argument, so the value has to pass with the correct datatype.

Example: Using remove() method to remove an element from the list

Here is a sample list that i have

my_list = [12, 'Siya', 'Tiya', 14, 'Riya', 12, 'Riya']

The list has elements of date-types string and number. The list has duplicate elements like number 12 and string Riya.

my_list = [12, 'Siya', 'Tiya', 14, 'Riya', 12, 'Riya'] my_list.remove(12) # it will remove the element 12 at the start. print(my_list) my_list.remove('Riya') # will remove the first Riya from the list print(my_list) my_list.remove(100) #will throw an error print(my_list)

Output:

['Siya', 'Tiya', 14, 'Riya', 12, 'Riya'] ['Siya', 'Tiya', 14, 12, 'Riya'] Traceback (most recent calllast): File "display.py", line 9, in my_list.remove(100) ValueError: list.remove(x): x not in the 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

List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()…)

Some of the list methods are mentioned in set 1 below

List Methods in Python | Set 1 (in, not in, len(), min(), max()…)

More methods are discussed in this article.

1. del[a : b] :- This method deletes all the elements in range starting from index ‘a’ till ‘b’ mentioned in arguments.

2. pop() :- This method deletes the element at the position mentioned in its arguments.






# Python code to demonstrate the working of
# del and pop()
# initializing list
lis = [2, 1, 3, 5, 4, 3, 8]
# using del to delete elements from pos. 2 to 5
# deletes 3,5,4
del lis[2 : 5]
# displaying list after deleting
print ("List elements after deleting are : ",end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")
print("\r")
# using pop() to delete element at pos 2
# deletes 3
lis.pop(2)
# displaying list after popping
print ("List elements after popping are : ", end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")

Output:

List elements after deleting are : 2 1 3 8 List elements after popping are : 2 1 8

3. insert(a, x) :- This function inserts an element at the position mentioned in its arguments. It takes 2 arguments, position and element to be added at respective position.

4. remove() :- This function is used to delete the first occurrence of number mentioned in its arguments.




# Python code to demonstrate the working of
# insert() and remove()
# initializing list
lis = [2, 1, 3, 5, 3, 8]
# using insert() to insert 4 at 3rd pos
lis.insert(3, 4)
# displaying list after inserting
print("List elements after inserting 4 are : ", end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")
print("\r")
# using remove() to remove first occurrence of 3
# removes 3 at pos 2
lis.remove(3)
# displaying list after removing
print ("List elements after removing are : ", end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")

Output:

List elements after inserting 4 are : 2 1 3 4 5 3 8 List elements after removing are : 2 1 4 5 3 8

5. sort() :- This function sorts the list in increasing order.

6. reverse() :- This function reverses the elements of list.




# Python code to demonstrate the working of
# sort() and reverse()
# initializing list
lis = [2, 1, 3, 5, 3, 8]
# using sort() to sort the list
lis.sort()
# displaying list after sorting
print ("List elements after sorting are : ", end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")
print("\r")
# using reverse() to reverse the list
lis.reverse()
# displaying list after reversing
print ("List elements after reversing are : ", end="")
for i in range(0, len(lis)):
print(lis[i], end=" ")

Output:

List elements after sorting are : 1 2 3 3 5 8 List elements after reversing are : 8 5 3 3 2 1

7. extend(b) :- This function is used to extend the list with the elements present in another list. This function takes another list as its argument.

8. clear() :- This function is used to erase all the elements of list. After this operation, list becomes empty.




# Python code to demonstrate the working of
# extend() and clear()
# initializing list 1
lis1 = [2, 1, 3, 5]
# initializing list 1
lis2 = [6, 4, 3]
# using extend() to add elements of lis2 in lis1
lis1.extend(lis2)
# displaying list after sorting
print ("List elements after extending are : ", end="")
for i in range(0, len(lis1)):
print(lis1[i], end=" ")
print ("\r")
# using clear() to delete all lis1 contents
lis1.clear()
# displaying list after clearing
print ("List elements after clearing are : ", end="")
for i in range(0, len(lis1)):
print(lis1[i], end=" ")

Output:

List elements after extending are : 2 1 3 5 6 4 3 List elements after clearing are :

Related articles:
List methods in Python
List Methods in Python | Set 1 (in, not in, len(), min(), max()…)

This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
School Programming
python-list
python-list-functions
Practice Tags :
python-list