Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Control Flow, Functions
  5. List As Arrays

List As Arrays

Arrays

Array is a collection of similar elements. Elements in the array can be accessed by index. Index starts with 0. Array can be handled in python by module named array

Syntax to import array

import array

Syntax to create array

Array_name = module_name.function_name(‘datatype’,[elements])

Example: Program to find sum of elements in array

import array
sum = 0
a = array.array('i',[1,2,3,4])
for i in a:
    sum = sum + i
print ("sum=",sum)

Output

sum= 10

To add items from list into array using fromlist( ) methodfromlist( ) function is used to append list to array

Syntax

arrayname.fromlist(list_name)
import array
a = array.array('i',[1,2,3,4])
c=[44,55,66]
a.fromlist(c)
print("New array: ",a)

Output,

New array:  array('i', [1, 2, 3, 4, 44, 55, 66])

Methods in Array

array

This function is used to create an array with data type and a list as specified in the argument

Syntax

array(data type, value in a list)

Example

array(‘i’,[10,20,30,40])

append

The append( ) method is used to add the element at the end of the array

Syntax

append( )

Example

import array
a = array.array('i',[10,20,30,40])
a.append(6)
print("New Array:",a)

Output

New Array: array('i', [10, 20, 30, 40, 6])

insert

The method insert( ) adds the element at the specified index

Syntax

insert(index,element)

Example

import array
a = array.array('i',[10,20,30,40])
a.insert(1,100)
print("New Array:",a)

Output

New Array: array('i', [10, 100, 20, 30, 40])

pop

The method pop( ) removes the element at the position mentioned in its argument and returns it

pop(index)

Example

import array
a = array.array('i',[10,20,30,40])
a.pop(1)
print("New Array:",a)

Output

New Array: array('i', [10, 30, 40])

index

The method index( ) returns the index of the element specified as argument

import array
a = array.array('i',[10,20,30,40])
print("Index of 20:",a.index(20))

Output

Index of 20: 1

reversed

The method reversed( ) when passed with an array returns an iterable with elements in reverse order

Syntax

reversed( )

Example

import array
a = array.array('i',[10,20,30,40])
print("Original array:",a)
res_arr=array.array('i',reversed(a))
print("Reversing array:",res_arr)

Output

Original array: array('i', [10, 20, 30, 40])
Reversing array: array('i', [40, 30, 20, 10])

count

The method count( ) returns number of times the element specified in the argument is present in the array

Syntax

count( element)

Example

import array
a = array.array('i',[10,20,30,40,30])
print("Number of elements:",a.count(30))

Output

Number of elements: 2

Loading

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments