Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - Remove Array Items



Removing array items in Python

Python arrays are a mutable sequence which means operation like adding new elements and removing existing elements can be performed with ease. We can remove an element from an array by specifying its value or position within the given array.

Thearray module defines two methods namely remove() and pop(). The remove() method removes the element by value whereas the pop() method removes array item by its position.

Python does not provide built-in support for arrays, however, we can use thearray module to achieve the functionality like an array.

Remove First Occurrence

To remove the first occurrence of a given value from the array, useremove() method. This method accepts an element and removes it if the element is available in the array.

Syntax

array.remove(v)

Where,v is the value to be removed from the array.

Example

The below example shows the usage of remove() method. Here, we are removing an element from the specified array.

import array as arr# creating arraynumericArray = arr.array('i', [111, 211, 311, 411, 511])# before removing arrayprint ("Before removing:", numericArray)# removing arraynumericArray.remove(311)# after removing arrayprint ("After removing:", numericArray)

It will produce the followingoutput

Before removing: array('i', [111, 211, 311, 411, 511])After removing: array('i', [111, 211, 411, 511])

Remove Items from Specific Indices

To remove an array element from specific index, use thepop() method. This method removes an element at the specified index from the array and returns the element at ith position after removal.

Syntax

array.pop(i)

Where,i is the index for the element to be removed.

Example

In this example, we will see how to use pop() method to remove elements from an array.

import array as arr# creating arraynumericArray = arr.array('i', [111, 211, 311, 411, 511])# before removing arrayprint ("Before removing:", numericArray)# removing arraynumericArray.pop(3)# after removing arrayprint ("After removing:", numericArray)

It will produce the followingoutput

Before removing: array('i', [111, 211, 311, 411, 511])After removing: array('i', [111, 211, 311, 511])
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp