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! Show
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() methodPython 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:
Example: Using remove() method to remove an element from the listHere 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 listHow to remove an element from a list in PythonPython 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.
The remove() methodThe 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() methodThe 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() methodThe 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 statementWe 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 ComprehensionThe 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.
Output: List elements after deleting are : 2 1 3 8 List elements after popping are : 2 1 83. 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.
Output: List elements after inserting 4 are : 2 1 3 4 5 3 8 List elements after removing are : 2 1 4 5 3 85. sort() :- This function sorts the list in increasing order. 6. reverse() :- This function reverses the elements of list.
Output: List elements after sorting are : 1 2 3 3 5 8 List elements after reversing are : 8 5 3 3 2 17. 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.
Output: List elements after extending are : 2 1 3 5 6 4 3 List elements after clearing are :Related articles: 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.
Article Tags :
Python School Programming
python-list python-list-functions Practice Tags :
python-list Python List Remove: How to Delete an Element From ListIn 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 RemoveContents
To Learn about Lists – Read Python List List Remove MethodThe 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: Program ExamplesRemoving an element from a listList = [1,3,2,4,6] List.remove(3) print (List)The result is as follows: [1, 2, 4, 6]Removing a tuple from the listList = [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 listList = ["Unix", "PHP", "Golang"] List.remove("PHP") print (List)The result is as follows: ['Unix', 'Golang']Removing duplicate elements in a listSocial_Media = ["Whatsapp", "Hike", "Facebook", "Whatsapp", "Telegram"] Social_Media.remove("Whatsapp") print (Social_Media)The result is as follows: Errors upon removing invalid itemsList = [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 listBest, 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() methodCreate 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. Example 2: Insert item using append() methodCreate 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. Example 3: Insert item using extend() methodCreate 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. |