Arrays in Python
Arrays in Python
UNIT-III
working with arrays using numPy - Creating arrays using numpy, numpy Attributes and
functions, Matrices in numpy.
Array in Python?
An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together.
This makes it easier to calculate the position of each element by simply adding an offset to a
base value, i.e., the memory location of the first element of the array (generally denoted by the
name of the array).
Or
Arrays are an ordered collection of elements of the same data type. Python arrays can only
hold a sequence of multiple items that are of the same type.
The Array can be handled in Python by a module named Array. It is useful when we must manipulate
only specific data values. The following are the terms to understand the concept of an array :
Element - Each item stored in an array is called an element.
Index - The location of an element in an array has a numerical index, which is used to identify the
element's position. The index value is very much important in an Array.
typecode − The typecode character used to speccify the type of elements in the array.
initializer − It is an optional value from which array is initialized. It must be a list, a bytes-like
object, or iterable elements of the appropriate type.
Minimum size
Type Code C Type Python Type
(bytes)
b signed char int 1
Unicode character;
u Py_UNICODE 2
deprecated since
Python 3.3
f float float 4
d double float 8
1. Arrays are similar to lists. The main difference is that arrays can store only one type of elements;
whereas, lists can store different types of elements. When dealing with a huge number of
elements, arrays use less memory than lists and they offer faster execution than lists.
2. The size of the array is not fixed in Python. Hence, we need not specify how many elements we
are going to store into an array in the beginning.
3. Arrays can grow or shrink in memory dynamically (during runtime).
4. Arrays are useful to handle a collection of elements like a group of numbers or characters.
5. Methods that are useful to process the elements of any array are available in 'array' module.
A list in Python is an inbuilt collection of items that can contain elements of multiple data
types, which may be either numeric, character logical values, etc.
It is an ordered collection supporting negative indexing.
A list can be created using [] containing data values. Contents of lists can be easily merged and
copied using Python’s inbuilt functions.
Example:
An array is a vector containing homogeneous elements i.e. belonging to the same data type.
Elements are allocated with contiguous memory locations.
PYTHON PROGRAMMING I YEAR/ I SEM MRCET
Typically the size of an array is fixed.
Arrays can be used by importing the array module.
Example:
# importing "array" for array creations
import array as arr
# creating an array with integer type
a = arr.array('i', [1, 2, 3])
print(type(a))
for i in a:
print(i, end=" ")
Output:
<class 'array.array'>
123
Example:
my_list = [1, 2, 3, 4] Example:
PYTHON PROGRAMMING I YEAR/ I SEM MRCET
import array
arr = array.array(‘i’, [1, 2, 3])
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
1.append() Method
This function is used to add the value mentioned in its arguments at the end of the array.
In this example, we are adding an element at the end of the array.
Syntax:arrayname.append(elmnt)
Example:
import array as arr
a=arr.array("i",[10,20,30,40])
a.append(50)
print(a)
2.clear() :The clear() method removes all the elements from an array
Syntax: arrayname.clear()
Example:
import array as arr
a=arr.array("i",[10,20,30,40,50])
a.clear()
print(a)
Output: array('i')
Syntax: arrayname.copy()
Example :
a=arr.array("i",[10,20,30,40,50])
b=arr.array("i")
b=copy.deepcopy(a)
print(b)
4.count() : The count() method returns the number of elements with the specified value.
Syntax: arrayname.count(value)
Example :
import array as arr
a=arr.array("i",[10,20,30,40,20])
b=a.count(20)
print(b)
Output: 2
5.extend() :The extend() method adds the specified list elements (or any iterable) to the end of the
current array.
Syntax :arrayname.extend(iterable)
Example:
import array as arr
a=arr.array("i",[10,20,30,40,20])
a.extend([50,60])
print(a)
6.index() :The index() method returns the position at the first occurrence of the specified value..
Syntax: arrayname.index(elmnt)
Example:
import array as arr
PYTHON PROGRAMMING I YEAR/ I SEM MRCET
a=arr.array("i",[10,20,30,40])
b=a.index(30)
print(b)
Output: 2
7.insert():The insert() method inserts the specified value at the specified position
Parameter Description
Example :
import array as arr
a=arr.array("i",[10,20,30,40])
a.insert(1,50)
print(a)
8.pop(): The pop() method removes the element at the specified position.
Syntax: arrayname.pop(pos)
Parameter Values
Parameter Description
pos Optional. A number specifying the position of the element you want to remove,
default value is -1, which returns the last item
Example:
import array as arr
a=arr.array("i",[10,20,30,40])
a.pop(1)
print(a)
PYTHON PROGRAMMING I YEAR/ I SEM MRCET
Output: array('i', [10, 30, 40])
9.remove():
The remove() method removes the first occurrence of the element with the specified value.
Syntax : arrayname.remove(elmnt)
Parameter Values
Parameter Description
elmnt Required. Any type (string, number, list etc.) The element you want to remove
Example:
import array as arr
a=arr.array("i",[10,20,30,40])
a.remove(30)
print(a)
10.reverse(): The reverse() method reverses the sorting order of the elements.
Syntax : arrayname.reverse()
Example:
import array as arr
a=arr.array("i",[10,20,30,40])
a.reverse()
print(a)
11.sort()
The sort() method sorts the list ascending by default.
You can also make a function to decide the sorting criteria(s).
reverse Optional. reverse=True will sort the list descending. Default is reverse=False
PYTHON PROGRAMMING I YEAR/ I SEM MRCET
key Optional. A function to specify the sorting criteria(s)
Example:
Slicing of an Array
Slice operation is performed on array with the use of colon(:).
To print elements from beginning to a range use [:Index], to print elements from end use [:-
Index], to print elements from specific Index till the end use [Index:]
To print elements within a range, use [Start Index:End Index] and to print whole List with the
use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1].
Example:
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end=" ")
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
Sliced_array = a[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_array)
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)
Output:
PYTHON PROGRAMMING I YEAR/ I SEM MRCET
Initial Array:
1 2 3 4 5 6 7 8 9 10
Slicing elements in a range 3-8:
array('i', [4, 5, 6, 7, 8])
Output
The new created array is : 1 2 3 1 2 5
The index of 1st occurrence of 2 is : 1
The index of 1st occurrence of 1 is : 0
PYTHON PROGRAMMING I YEAR/ I SEM MRCET