ARRAY OPERATIONS IN PYTHON

 ARRAY OPERATIONS IN PYTHON :Arrays are used to store multiple values in one single variable:

Example

Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).

Example

Return the number of elements in the cars array:

x = len(cars)

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Example

Print each item in the cars array:

for x in cars:
  print(x)

Adding Array Elements

You can use the append() method to add an element to an array.

Example

Add one more element to the cars array:

cars.append("Honda")

Removing Array Elements

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

Example

Delete the second element of the cars array:

cars.pop(1)

Example

Delete the element that has the value "Volvo":

cars.remove("Volvo")

Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append():Adds an element at the end of the list

clear():Removes all the elements from the list

copy():Returns a copy of the list

count():Returns the number of elements with the specified value

extend():Add the elements of a list (or any iterable), to the end of the current list

index():Returns the index of the first element with the specified value

insert():Adds an element at the specified position

pop():Removes the element at the specified position

remove():Removes the first item with the specified value

reverse():Reverses the order of the list

sort():Sorts the list

example:

import array as arr

numbers = arr.array('i', [1, 2, 3])

numbers.append(4)
print(numbers)     # Output: array('i', [1, 2, 3, 4])

# extend() appends iterable to the end of the array
numbers.extend([5, 6, 7])
print(numbers)     
import array as arr

number = arr.array('i', [1, 2, 3, 3, 4])

del number[2]  # removing third element
print(number)  # Output: array('i', [1, 2, 3, 4])

del number  # deleting entire array
print(number)  
import array as arr

numbers = arr.array('i', [10, 11, 12, 12, 13])

numbers.remove(12)
print(numbers)   # Output: array('i', [10, 11, 12, 13])

print(numbers.pop(2))   # Output: 12
print(numbers)  

Posted on by