What are the 3 ways of deleting an element from a list Explain with examples?

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!

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 <module> my_list.remove(100) ValueError: list.remove(x): x not in the list

How to remove an element from a list in Python

Python provides the following methods to remove one or multiple elements. We can delete the elements using the del keyword by specifying the index position. Let's understand the following methods.

  • remove()
  • pop()
  • clear()
  • del
  • List Comprehension - If specified condition is matched.

The remove() method

The remove() method is used to remove the specified value from the list. It accepts the item value as an argument. Let's understand the following example.

Example -

Output:

The list is: ['Joseph', 'Bob', 'Charlie', 'Bob', 'Dave'] After removing element: ['Bob', 'Charlie', 'Bob', 'Dave']

If the list contains more than one item of the same name, it removes that item's first occurrence.

Example -

Output:

The list is: ['Joseph', 'Bob', 'Charlie', 'Bob', 'Dave'] After removing element: ['Joseph', 'Charlie', 'Bob', 'Dave']

The pop() method

The pop() method removes the item at the specified index position. If we have not specified the index position, then it removes the last item from the list. Let's understand the following example.

Example -

Output:

The list is: ['Joseph', 'Bob', 'Charlie', 'Bob', 'Dave'] After removing element: ['Joseph', 'Bob', 'Charlie', 'Dave'] After removing element: ['Joseph', 'Bob', 'Charlie']

We can also specify the negative index position. The index -1 represents the last item of the list.

Example -

Output:

The list is: ['Joseph', 'Bob', 'Charlie', 'Bob', 'Dave'] After removing element: ['Joseph', 'Bob', 'Charlie', 'Dave']

The clear() method

The clear() method removes all items from the list. It returns the empty list. Let's understand the following example.

Example -

Output:

[10, 20, 30, 40, 50, 60] []

The del statement

We can remove the list item using the del keyword. It deletes the specified index item. Let's understand the following example.

Example -

Output:

[10, 20, 30, 40, 50, 60] [10, 20, 30, 40, 50] [10, 20, 30, 40]

It can delete the entire list.

Output:

Traceback (most recent call last): File "C:/Users/DEVANSH SHARMA/PycharmProjects/Practice Python/first.py", line 14, in print(list1) NameError: name 'list1' is not defined

We can also delete the multiple items from the list using the del with the slice operator. Let's understand the following example.

Example -

Output:

[10, 20, 30, 40, 50, 60] [10, 40, 50, 60] [60] []

Using List Comprehension

The list comprehension is slightly different way to remove the item from the list. It removes those items which satisfy the given condition. For example - To remove the even number from the given list, we define the condition as i % 2 which will give the reminder 2 and it will remove those items that's reminder is 2.

Let's understand the following example.

Example -

Output:

[20, 34, 40, 60] [11, 45]

Next TopicHow to Round number in Python


← prev next →


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.

What are the 3 ways of deleting an element from a list Explain with examples?




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

Python List Remove: How to Delete an Element From List

In Python, Integer or float objects, for example, are primitive data types that can’t be further mutilated. Furthermore, these data types are immutable, meaning that they can’t be modified once they have been assigned. Thus, it doesn’t make any sense to think of changing the value of an integer.

Lists are defined by enclosing a comma-separated series of items in square brackets ([ ]),

If you need a different integer, then you assign a different one. No need to modify the existing one.

Python List remove()

In this tutorial, we will learn about the Python List remove() method with the help of examples.

The remove() method removes the first matching element (which is passed as an argument) from the list.

Example

# create a list prime_numbers = [2, 3, 5, 7, 9, 11]
# remove 9 from the list prime_numbers.remove(9)
# Updated prime_numbers List print('Updated List: ', prime_numbers) # Output: Updated List: [2, 3, 5, 7, 11]

Python List Remove

Contents

  • 1 List Remove Method
  • 2 How does the Remove() function work?
  • 3 Program Examples
    • 3.1 Removing an element from a list
    • 3.2 Removing a tuple from the list
    • 3.3 Delete a string from the list
    • 3.4 Removing duplicate elements in a list
    • 3.5 Errors upon removing invalid items

To Learn about Lists – Read Python List

List Remove Method

The Remove Module is a built-in list method that allows you to delete values in a list.

It deletes the first occurrence of a value in a sequence, i.e., it won’t erase all the instances if exist in the list.

The remove() method has the following syntax:

List_name.remove(<element_value>)

It takes the element_value as an input argument. The function searches the list for the matching element_value and removes the first occurrence of the element_value from the list.

It doesn’t have a return value. It only removes the element from a list without returning a value.

How does the Remove() function work?

When we pass an input value to the remove(), the list gets iterated through each element until the matching onegets found.

This matching element gets removed from the list, and the indexes of all items of the list get also updated. If an invalid or non-existent element provided as input, then the function raises a ValueError exception.

The flowchart below attempts to explain it in a diagram:

What are the 3 ways of deleting an element from a list Explain with examples?

Program Examples

Removing an element from a list

List = [1,3,2,4,6] List.remove(3) print (List)

The result is as follows:

[1, 2, 4, 6]

Removing a tuple from the list

List = [1,2,(4,6),(25,4)] List.remove((4,6)) print (List)

The output is as follows:

[1, 2, (25, 4)]

Delete a string from the list

List = ["Unix", "PHP", "Golang"] List.remove("PHP") print (List)

The result is as follows:

['Unix', 'Golang']

Removing duplicate elements in a list

Social_Media = ["Whatsapp", "Hike", "Facebook", "Whatsapp", "Telegram"] Social_Media.remove("Whatsapp") print (Social_Media)

The result is as follows:

['Hike', 'Facebook', 'Whatsapp', 'Telegram']

Errors upon removing invalid items

List = [1,2, "Linux", "Java", 25, 4, 9] List.remove("PHP") print (List)

The result is as follows:

Traceback (most recent call last): File "C:\Python\Python35\test.py", line 3, in <module> List.remove("PHP") ValueError: list.remove(x): x not in list

Best,

TechBeamers

Methods:

Many methods exist in Python to modify the list. Some common methods to add and remove data in the list are mentioned here.

insert (index,item): This method is used to insert any item in the particular index of the list and right shift the list items.

append (item): This method is used to add new element at the end of the list.

extend (anotherList): The items of one list can be inserted at the end of another list by using this method.

remove (item): This method is used to remove particular item from the list.

pop (index): The method is used to remove item from the list based on index value.

del(): This method is used to remove the particular item of the list or slice the list.

clear(): This method is used to remove all items of a list

Add items into the list:

Different ways to add items in Python list are shown in this part of the tutorial.

Example 1: Insert item using insert() method

Create a python file with the following script to see the use of insert() method. A new item will be inserted in the third position of the list and the other items will be shifted right after running the script.

# Declare list
listdata = [89, 56, 90, 34, 89, 12]

# Insert data in the 2nd position
listdata.insert(2, 23)

# Displaying list after inserting
print("The list elements are")

for i in range(0, len(listdata)):
print(listdata[i])

Output:

The following output will appear after running the script.

What are the 3 ways of deleting an element from a list Explain with examples?

Example 2: Insert item using append() method

Create a python file with the following script to see the use of append() method. It is mentioned before that append() method inserts data at the end of the list. So, ‘Toshiba’ will be inserted at the end of listdata after running the script.

# Define the list
listdata = ["Dell", "HP", "Leveno", "Asus"]

# Insert data using append method
listdata.append("Toshiba")

# Display the list after insert
print("The list elements are")

for i in range(0, len(listdata)):
print(listdata[i])

Output:

The following output will appear after running the script.

What are the 3 ways of deleting an element from a list Explain with examples?

Example 3: Insert item using extend() method

Create a python file with the following script to see the use of extend() method. Here, two lists are declared in the script which are combined together by using extend() method. The items of the second list will be added at the end of the first list.

# initializing the first list
list1 = ['html', 'CSS', 'JavaScript', 'JQuery']

# initializing the second list
list2 = ['PHP', 'Laravel', 'CodeIgniter']

# Combine both lists using extend() method
list1.extend(list2)

# Display the list after combing
print ("The list elements are :")

for i in range(0, len(list1)):
print(list1[i])

Output:

The following output will appear after running the script.

What are the 3 ways of deleting an element from a list Explain with examples?