Which of the following can delete an element from a list if the 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

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.

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
Read Full Article

Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề