Python list delete elements by indexes

Python Remove from List by Index

How to remove an element/item from a list by index in Python? To remove an element from a list by index use the list.remove() , pop() , enumerate() , List comprehension , and del keyword. In this article, I will explain by using all these methods with examples.

1. Quick Examples of Remove from List by Index

If you are in a hurry, below are some quick examples of how to remove items from the list by index.

 # Quick examples to remove item from list by index # Example 1: Using remove() by Index technology = ["Hadoop", "Spark", "Python","Java", "Pandas"] technology.remove(technology[1]) # Example 2: Using pop() function numbers = [2, 5, 8, 4, 1, 7, 3, 9] numbers.pop(3) # Example 3: Using del keyword del numbers[i] # Example 3: Remove multiple elements by index numbers = [2, 5, 8, 4, 1, 7, 3, 9] indixes=[2,4] for i in sorted(indixes, reverse=True): del numbers[i] # Example 4: Remove element by index # Using enumerate() + loop numbers = [2, 5, 8, 4, 1, 7, 3, 9] indixes=[2,4,6] num = [] for ind, ele in enumerate(numbers): if ind not in indixes: num.append(ele) # Example 5: Remove an element by index # Using enumerate() + List Comprehension numbers = [2, 5, 8, 4, 1, 7, 3, 9, 14] indixes=[2, 4, 6, 8] num = [ele for idx, ele in enumerate(numbers) if idx not in indixes] 

2. Syntax of remove()

Following is a syntax of the remove().

 # Using remove() with element mylist.remove(element) # Using remove() with index position mylist.remove(mylist[index]) 

Here, mylist is the list object from where the element is removed.

3. Remove List Item by Index in Python using remove()

To remove a list item/element by Index use the remove(list[index]) in Python, you can use this only if you know the index of the element you wanted to remove. Note that the remove() method doesn’t take the index as an argument however, you can get the element by index using list[index] and use the value to the method. Let’s create a list named technology and remove the Spark element from it by using an index.

 # Consider the list of strings technology = ["Hadoop", "Spark", "Python","Java", "Pandas"] print("Actual List: ",technology) # Using remove() by Index technology.remove(technology[1]) print("Final List: ",technology) 

This example yields the below output.

python remove list by index

Here it removed the element from the 1st index which is the 2nd element from the list (Index starts from 0).

4. Remove Element from the List by Index using pop()

You can use the pop() method to remove an item/element from a list by its index, this takes the index as an argument and returns the removed item, so it can be stored in a variable if needed.

 # Use pop() to remove item from the list by index numbers = [2, 5, 8, 4, 1, 7, 3, 9] numbers.pop(3) print(numbers) # Output: # [2, 5, 8, 1, 7, 3, 9] 

Here, it removed the element from the 3rd index which is the 4th element from the list.

Читайте также:  Two dimensional list to list python

5. Using del Keyword

Similarly, you can use the del keyword to delete the element by index.

 # Use del keyword numbers = [2, 5, 8, 4, 1, 7, 3, 9] del numbers[3] print(numbers) # Output: # [2, 5, 8, 1, 7, 3, 9] 

6. Remove Multiple Elements from List by Index

To remove the multiple elements/items from the python list by index, you can use any above-mentioned methods, however, I will use the del keyword to explain. In order to use this you need a list of element indexes you wanted to remove and use it with for loop to remove iteratively.

Here, the sorted() function sorts the list of indices in reverse order to ensure that the removal of elements at lower indices won’t affect the index specifications of elements at larger indices.

 # Consider list technology = ["Hadoop", "Spark", "Python","Java", "Pandas"] print("Actual List: ",technology) # Consider list of indexes to remove indexes=[2,4] # Remove multiple elements from list for i in sorted(indexes, reverse=True): del technology[i] print("Final List: ",technology) # Output: # Actual List: ['Hadoop', 'Spark', 'Python', 'Java', 'Pandas'] # Final List: ['Hadoop', 'Spark', 'Java'] 

7. Using enumerate() + Loop

You can use enumerate() and a loop in Python to remove elements from a list based on a condition. For example, the loop uses enumerate() to iterate over the elements in the list numbers. For each iteration, the i variable holds the index of the current element and the num variable holds the value of the current element. In the end, the num list holds all the elements from numbers except the ones at the indices specified in indexes.

 # Using enumerate() + loop numbers = [2, 5, 8, 4, 1, 7, 3, 9] print("Actual List: ",numbers) indixes=[2,4,6] num = [] for ind, ele in enumerate(numbers): # checking if element not present in index list if ind not in indixes: num.append(ele) print("Final List: ",num) # Output: # Actual List: [2, 5, 8, 4, 1, 7, 3, 9] # Final List: [2, 5, 4, 7, 9] 

8. Using enumerate() + List Comprehension

You can also remove elements from a list at a specific index using enumerate() and list comprehension. For example, the list comprehension uses enumerate() to loop through the elements in the numbers list and checks the index against the indixes list. If the index is not in the indexes list, the element is added to the num list. The result is a new list num containing the elements of numbers that were not removed.

 # Remove element by index # Using enumerate() + List Comprehension numbers = [2, 5, 8, 4, 1, 7, 3, 9, 14] print("Actual List: ",numbers) indixes=[2, 4, 6, 8] # Using enumerate() + List Comprehension num = [ele for idx, ele in enumerate(numbers) if idx not in indixes] print("Final List: ",num) # Output # Actual List: [2, 5, 8, 4, 1, 7, 3, 9, 14] # Final List: [2, 5, 4, 7, 9] 

Conclusion

In this Python article, I have explained how to remove an element/item from a list by index and remove multiple elements by using methods like list.remove() , del statement, pop() , List comprehension , and enumerate() functions with examples.

Читайте также:  Column css break after

References

You may also like reading:

Источник

How to remove elements from a list in Python?

Remove Elements Python List Featured Image

In this article, we will go through all the methods to remove elements from a list in Python.

Python lists are the most basic data structure used in day-to-day programming. We come across situations where we need to remove elements from lists and in this article, we’ll discuss exactly that.

1. Remove Elements From a List Based on the Values

One of the reasons Python is a renowned programming language is the presence of the numerous inbuilt functions. These inbuilt functions are very handy and thereby make Python very convenient to write.

remove() function

Python has an inbuilt function, remove() that helps us to remove elements based on the value.

# List of integers lis = [3, 1, 4, 1, 5, 9, 2, 6, 5] # Remove element with value = 1 lis.remove(1) # Printing the list print(lis) # Remove element with value = 9 lis.remove(9) # Printing the list print(lis)
[3, 4, 1, 5, 9, 2, 6, 5] [3, 4, 1, 5, 2, 6, 5]

The key things to note here are:

  • The remove() function takes in one argument — the value to be removed.
  • If there are multiple occurrences of the given value, the first one is removed.
  • Removing an element does not leave a blank space at that position, it just shifts the following elements to the left.
  • In case, there is no such element in the list, then the script raises an error.

Error-free usage of remove() function

There is an easy way to bypass the error while removing an element in case the programmer is unaware of its presence on the list. We’ll do this using the if condition.

# List of integers lis = [1, 4, 2, 6, 1, 9, 10] # Value to be removed val = 6 # Check if the list contains the value if val in lis: # Remove the value from the list lis.remove(val) # Printing the list print(lis)

In the above code snippet, we first check the presence of the value in the list before removing.

Remove all the occurrences of a value in a list

As we previously mentioned, remove() function only removes the first occurrence of a value. In order to take out all the instances of said value, we will do use the while loop.

# List of integers lis = [1, 4, 2, 6, 1, 9, 10] # Value to be removed val = 1 # Run until the list containes the value while val in lis: # Remove the value from the list lis.remove(val) # Printing the list print(lis)

This sums up the usage of remove() function.

2. Removing elements based on an index

There can be a few ways to remove elements based on the index. Let us quickly go through each one of them.

del keyword

del is a powerful tool in Python which is used to remove entire objects. It can also be used to remove elements from a given list.

# List of integers lis = [3, 1, 4, 1, 5, 9, 2, 6, 5] # Removing element from the start (index = 0) del lis[0] # Printing the list print(lis) # Removing element from the last (index = -1) del lis[-1] # Printing the list print(lis)
[1, 4, 1, 5, 9, 2, 6, 5] [1, 4, 1, 5, 9, 2, 6]

Some of the observations derived from the above script are:

  • del is not a method. It is a statement that deletes the item placed after it.
  • Removing an element from a specific index shifts the next value to that specific index if it is not the last index.
  • Providing an index more than (or equal to) the length of the list will raise an “out of range” error.
Читайте также:  Java duration between localdate

pop() function

As the name suggests, pop() function pops out an element from a specified index.

# List of integers lis = [3, 1, 4, 1, 5, 9, 2, 6, 5] # Removing the fourth element (index = 3) lis.pop(3) # Printing the list print(lis) # Removing the second last element (index = -2) lis.pop(-2) # Printing the list print(lis)
[3, 1, 4, 5, 9, 2, 6, 5] [3, 1, 4, 5, 9, 2, 5]

What we learnt about pop() method here is:

  • It takes a single argument — the index of a list
  • It removes the element from the list based on the given index. The following elements shift to the left.
  • It supports backward indexing.
  • It will raise an “out of range” error if the index is not present for the list.

We have a complete article on the use of pop() method.

3. Removing a range of elements from a list

Python has a provision of removing a range of elements from a list. This can be done by del statement.

# List of integers lis = [3, 1, 4, 1, 5, 9, 2, 6, 5] # Removing first and second element del lis[0:2] # Printing the list print(lis) # Removing last two elements del lis[-2:] # Printing the list print(lis)

Let us try to understand the process:

  • To remove multiple elements from a list in a sequence, we need to provide a range of elements to the del statement.
  • A range of elements take a starting index and/or an ending index, separated by a colon ‘:’ .
  • The values to be deleted include starting index, but not the value at the ending index.
  • In case, the ending index is missing, the range includes all the elements till the end of the list.

4. Remove all the elements from the list

Python provides a method to empty the entire list in a single line.

# List of integers lis = [3, 1, 4, 1, 5, 9, 2, 6, 5] # Removing all elements lis.clear() # Printing the list print(lis)

If the function applied to an empty list, it does not raise any error.

Conclusion

It is up to your discretion to use the way of removing elements from a list, either by value or index. Different circumstances require a different approach, therefore Python provides various methods of removing elements from a Python list.

We hope the reader had no difficulty in following the article. Feel free to comment below for any queries related to the subject.

Источник

Оцените статью