Remove items from array python

Remove Element from an Array/List in Python

This tutorial will go through some common ways for removing elements from Python arrays/lists.

Arrays or Lists?

Python’s built-in sequence representation is a list, defined as a heterogenous sequence of elements, where each element has a definitive index in the sequence. To use arrays, you’d have to import the array module, which does ship with Python itself, but lists are far more commonly used.

Additionally — since the list syntax looks a lot like the syntax you’d use to define arrays in other programming languages — the terms «array» and «list» are oftentimes used interchangeably, even though they’re not the same data structure. It’s worth noting that many of these methods work both for an array and a list!

Using remove()

Appropriately, the remove() function can be used on any array or list in Python. To use it, we can simply pass the value of the element we want to remove. Let’s imagine we have the following array:

array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] 

To remove, say, element 40 , we would simply write:

Читайте также:  Javascript свое модальное окно

The result is the same array without the value 40 :

[10, 20, 30, 50, 60, 70, 80, 90, 100] 

Using pop()

The pop() function accepts the index of the element we want to remove. If we had the same array/list as before (with values from 10 to 100), we could write something like the following:

If we printed the result of the pop method, it would be the value 40 :

[10, 20, 30, 50, 60, 70, 80, 90, 100] 

Similarly to how pop() works in the stack data structure, here pop() also returns the value that it had just removed.

The only difference is that with arrays, we can remove an arbitrary element. With stacks, only the top element (i.e. the last one added) can ever be removed.

Using del

del is a python keyword used for deleting objects. Its exact behavior changes depending on the context, so we can also use it to remove list elements, though, arrays don’t support this. Once again, let’s take the same array and index as before:

array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] index = 3 

To remove the element at index 3 , we simply type the following:

If we now printed the contents of our array, we would get the following output:

[10, 20, 30, 50, 60, 70, 80, 90, 100] 

Using numpy Arrays

NumPy arrays are commonly used (especially in machine learning), so let’s show one of the ways to remove an element from a numpy array. Before using numpy , it is necessary to import it with:

To create a numpy array, we can wrap our current list using np.array() as such:

Alternatively, we could also declare a new array inside the method call itself:

a = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) 

Now to remove an element at index 3 , we use the following code:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

index = 3 a = np.delete(a, index) 

delete() is a static method declared in the numpy module. It accepts the array and the index of the element to remove.

The method returns a new array without the removed element:

[10, 20, 30, 50, 60, 70, 80, 90, 100] 

Conclusion

There are different ways to remove a list element in Python. Sometimes we might want to remove an element by index and sometimes by value. Sometimes we’re using Python’s default array and sometimes a numpy array.

In all these cases, it’s good to have multiple options to help us decide which of the techniques to use.

Источник

Python Remove Array Item

You can use the pop() method to remove an element from the array.

Example

Delete the second element of the cars array:

You can also use the remove() method to remove an element from the array.

Example

Delete the element that has the value «Volvo»:

Note: The list’s remove() method only removes the first occurrence of the specified value.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python List .remove() — How to Remove an Item from a List in Python

Dionysia Lemonaki

Dionysia Lemonaki

Python List .remove() - How to Remove an Item from a List in Python

In this article, you’ll learn how to use Python’s built-in remove() list method.

By the end, you’ll know how to use remove() to remove an item from a list in Python.

Here is what we will cover:

The remove() Method — A Syntax Overview

The remove() method is one of the ways you can remove elements from a list in Python.

The remove() method removes an item from a list by its value and not by its index number.

The general syntax of the remove() method looks like this:

  • list_name is the name of the list you’re working with.
  • remove() is one of Python’s built-in list methods.
  • remove() takes one single required argument. If you do not provide that, you’ll get a TypeError – specifically you’ll get a TypeError: list.remove() takes exactly one argument (0 given) error.
  • value is the specific value of the item that you want to remove from list_name .

The remove() method does not return the value that has been removed but instead just returns None , meaning there is no return value.

If you need to remove an item by its index number and/or for some reason you want to return (save) the value you removed, use the pop() method instead.

How to Remove an Element from a List Using the remove() Method in Python

To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method.

remove() will search the list to find it and remove it.

#original list programming_languages = ["JavaScript", "Python", "Java", "C++"] #print original list print(programming_languages) # remove the value 'JavaScript' from the list programming_languages.remove("JavaScript") #print updated list print(programming_languages) #output #['JavaScript', 'Python', 'Java', 'C++'] #['Python', 'Java', 'C++'] 

If you specify a value that is not contained in the list, then you’ll get an error – specifically the error will be a ValueError :

programming_languages = ["JavaScript", "Python", "Java", "C++"] #I want to remove the value 'React' programming_languages.remove("React") #print list print(programming_languages) #output # line 5, in #programming_languages.remove("React") #ValueError: list.remove(x): x not in list 

To avoid this error from happening, you could first check to see if the value you want to remove is in the list to begin with, using the in keyword.

It will return a Boolean value – True if the item is in the list or False if the value is not in the list.

programming_languages = ["JavaScript", "Python", "Java", "C++"] #check if 'React' is in the 'programming_languages' list print("React" in programming_languages) #output #False 

Another way to avoid this error is to create a condition that essentially says, «If this value is part of the list then delete it. If it doesn’t exist, then show a message that says it is not contained in the list».

programming_languages = ["JavaScript", "Python", "Java", "C++"] if "React" in programming_languages: programming_languages.remove("React") else: print("This value does not exist") #output #This value does not exist 

Now, instead of getting a Python error when you’re trying to delete a certain value that doesn’t exist, you get a message returned, saying the item you wanted to delete is not in the list you’re working with.

The remove() Method Removes the First Occurrence of an Item in a List

A thing to keep in mind when using the remove() method is that it will search for and will remove only the first instance of an item.

This means that if in the list there is more than one instance of the item whose value you have passed as an argument to the method, then only the first occurrence will be removed.

Let’s look at the following example:

programming_languages = ["JavaScript", "Python", "Java", "Python", "C++", "Python"] programming_languages.remove("Python") print(programming_languages) #output #['JavaScript', 'Java', 'Python', 'C++', 'Python'] 

In the example above, the item with the value of Python appeared three times in the list.

When remove() was used, only the first matching instance was removed – the one following the JavaScript value and preceeding the Java value.

The other two occurrences of Python remain in the list.

What happens though when you want to remove all occurrences of an item?

Using remove() alone does not accomplish that, and you may not want to just remove the first instance of the item you specified.

How to Remove All Instances of an Item in A List in Python

One of the ways to remove all occurrences of an item inside a list is to use list comprehension.

List comprehension creates a new list from an existing list, or creates what is called a sublist.

This will not modify your original list, but will instead create a new one that satisfies a condition you set.

#original list programming_languages = ["JavaScript", "Python", "Java", "Python", "C++", "Python"] #sublist created with list comprehension programming_languages_updated = [value for value in programming_languages if value != "Python"] #print original list print(programming_languages) #print new sublist that doesn't contain 'Python' print(programming_languages_updated) #output #['JavaScript', 'Python', 'Java', 'Python', 'C++', 'Python'] #['JavaScript', 'Java', 'C++'] 

In the example above, there is the orginal programming_languages list.

Then, a new list (or sublist) is returned.

The items contained in the sublist have to meet a condition. The condition was that if an item in the original list has a value of Python , it would not be part of the sublist.

Now, if you don’t want to create a new list, but instead want to modify the already existing list in-place, then use the slice assignment combined with list comprehension.

With the slice assignment, you can modify and replace certain parts (or slices) of a list.

To replace the whole list, use the [:] slicing syntax, along with list comprehension.

The list comprehension sets the condition that any item with a value of Python will no longer be a part of the list.

programming_languages = ["JavaScript", "Python", "Java", "Python", "C++", "Python"] programming_languages[:] = (value for value in programming_languages if value != "Python") print(programming_languages) #output #['JavaScript', 'Java', 'C++'] 

Conclusion

And there you have it! You now know how to remove a list item in Python using the remove() method. You also saw some ways of removing all occurrences of an item in a list in Python.

I hope you found this article useful.

To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.

You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.

Thanks for reading and happy coding 😊 !

Источник

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