DEV Community

shiva yada
shiva yada

Posted on • Edited on

Array Methods (Python)

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

  • append()

Adds an element at the end of the array/list

import array as ar
a= ar.array('i',[1,2,3,5])
a.append(7)
print(a)
#output:  array('i',[1,2,3,5,7])
Enter fullscreen mode Exit fullscreen mode
  • insert(pos, value)

Inserts an element at desired position of the array

import array 
a= array('i',[1,2,3,5])
a.insert(1,7)
print(a)
#output:  array('i',[1,7,2,3,5])
Enter fullscreen mode Exit fullscreen mode
  • remove(value)

To remove an element from the array.

import array 
a= array('i',[1,2,3,5])
a.remove(3)
print(a)
#output:  array('i',1,2,5])
Enter fullscreen mode Exit fullscreen mode
  • extend(arr)

Adding another array to a existing array using extend method

import array 
a= array('i',[1,2,3,5])
a.extend([33,55])
print(a)
#output:  array('i',[1,2,3,5,33,55])
Enter fullscreen mode Exit fullscreen mode
  • pop()

Pop method removes the last element in array

import array 
a= array('i',[1,2,3,5])
a.pop()
print(a)
#output:  array('i',[1,2,3])
Enter fullscreen mode Exit fullscreen mode
  • index(value)

To know the index of a value in an array using index(val) method.

import array 
a= array('i',[1,2,3,5])
print(a.index(3))
#output: 2
Enter fullscreen mode Exit fullscreen mode
  • reverse()

To reverse an array use reverse() method

import array 
a= array('i',[1,2,3,5])
a.reverse()
print(a)
#output:  array('i',[5,3,2,1])
Enter fullscreen mode Exit fullscreen mode
  • fromlist(list)

fromlist() is used to add a list to the end of the array. It will take a list as its input argument and the output of this function is an array with list appended at the end of the array.

import array 
a= array('i',[1,2,3,5])
a.fromlist([10,7,3])
print(a)
#output:  array('i',[1,2,3,5,10,7,3])
Enter fullscreen mode Exit fullscreen mode
  • count(val)

count() will tell the total number of occurrences of the given value in the array.

import array 
a= array('i',[1,2,3,3,3,3,5])
print(a.count(3))
#output:  4
Enter fullscreen mode Exit fullscreen mode

Resources

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs