Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python Unpack Array
Next article icon

Removing items from an array can be a common task, and there are several ways to accomplish this depending on the specific needs of your application. This article will cover different methods to remove items from an array inPython.

Remove specific array item

Theremove() method removes the first occurrence of a specified value from the array. If the value is not found, it raises a ValueError.

Python
importarray# Create an array of integersarr=array.array('i',[1,2,3,4,5])# Remove the first occurrence of the value 3arr.remove(3)print(arr)

Output
array('i', [1, 2, 4, 5])

Let's take a look at other cases of removing item from an array:

Using Slicing to remove item

You can useslicing to remove elements from an array by creating a new array that excludes the elements you want to remove. This method is useful when you need to remove items at specific positions.

Python
importarray# Create an array of integersarr=array.array('i',[1,2,3,4,5])# Remove the element at index 2 (third element)arr=arr[:2]+arr[3:]print(arr)

Output
array('i', [1, 2, 4, 5])

Remove item at specific index - Using pop()

Thepop() method removes an element at a specified index and returns it. If no index is specified, it removes and returns the last element of the array.

Python
importarray# Create an array of integersarr=array.array('i',[1,2,3,4,5])# Remove the element at index 2 and return itval=arr.pop(2)print(arr)print(val)

Output
array('i', [1, 2, 4, 5])3

Using List Comprehension

Although this method is more suited tolists, it can also be used with arrays for more complex removal operations such as removing all occurrences of a value.

Python
importarray# Create an array of integersarr=array.array('i',[1,2,3,2,4,2,5])# Remove all occurrences of the value 2arr=array.array('i',[xforxinarrifx!=2])print(arr)

Output
array('i', [1, 3, 4, 5])



Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp