0% found this document useful (0 votes)
30 views

Arrays in Python

Uploaded by

abhinavicon789
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Arrays in Python

Uploaded by

abhinavicon789
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

PYTHON PROGRAMMING I YEAR/ I SEM MRCET

UNIT-III

Arrays: Definition, Advantages of Arrays, Creating an Array, Operations on Arrays, Arrays vs


List,Importing the Array Module, Indexing and Slicing on Arrays,

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.

from array import *


arrayName = array(typecode, [initializers])

 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.

How to Import Python Array Module?


There are three ways you can import the array module:
1. By using import array
import array
#how you would create an array
array.array()
PYTHON PROGRAMMING I YEAR/ I SEM MRCET
2. import array as arr
#how you would create an array
arr.array()
3. from array import *, with * importing all the functionalities available.
from array import *
#how you would create an array
array()

Minimum size
Type Code C Type Python Type
(bytes)
b signed char int 1

B unsigned char int 1

Unicode character;
u Py_UNICODE 2
deprecated since
Python 3.3

h signed short int 2

H unsigned short int 2

i signed int int 2

I unsigned int int 2

l signed long int 4

L unsigned long int 4

q signed long long int 8

Q unsigned long long int 8

f float float 4

d double float 8

Create an Array in Python


 Array in Python can be created by importing an array module.
import array as arr
 array( data_type , value_list ) is used to create array in Python with data type and value
list specified in its arguments.
 In below code Python create array : one of integers and one of doubles . It then prints the
contents of each array to the console.
import array as arr
PYTHON PROGRAMMING I YEAR/ I SEM MRCET
a = arr.array('i', [1, 2, 3])
print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe new created array is : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")
Output:
The new created array is : 1 2 3

The new created array is : 2.5 3.2 3.3


Accessing Elements from the Array
 In order to access the array items refer to the index number. Use the index operator [ ] to
access an item in a array in Python. The index must be an integer.
 Below, code shows first how to Python import array and use of indexing to access elements in
arrays.
 The a[0] expression accesses the first element of the array a , which is 1.
 The a[3] expression accesses the fourth element of the array a , which is 4.
 Similarly, the b[1] expression accesses the second element of the array b , which is 3.2, and
the b[2] expression accesses the third element of the array b , which is 3.3.

import array as arr


a = arr.array('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])
Output
Access element is: 1
Access element is: 4
Access element is: 3.2
Access element is: 3.3

Advantages and Disadvantages of Array in Python


PYTHON PROGRAMMING I YEAR/ I SEM MRCET
Advantages of arrays

The following are some advantages of arrays:

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.

Disadvantages of Array in Python

1. Once created, you cannot easily change their size.


2. Adding or removing elements in the middle can be slow.
3. You can only store elements of the same type.
4. Finding something in an array can take time, especially in large arrays.
5. They don’t support key-value pairs like dictionaries do.
Array Vs List

What are Lists?

 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:

sample_list = [1, "Yash", ['a', 'e']]


print(type(sample_list))
print(sample_list)
Output:
<class 'list'>
[1, 'Yash', ['a', 'e']]

What are Arrays?

 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

Difference Between List and Array in Python


 The following table shows the differences between List and Array in Python:

Can consist of elements belonging to Only consists of elements belonging to the


different data types same data type
No need to explicitly import a module for Need to explicitly import
the declaration the array module for declaration
Cannot directly handle arithmetic
Can directly handle arithmetic operations
operations
Preferred for a shorter sequence of data Preferred for a longer sequence of data
items items
Greater flexibility allows easy Less flexibility since addition, and
modification (addition, deletion) of data deletion has to be done element-wise
The entire list can be printed without any A loop has to be formed to print or access
explicit looping the components of the array
Consume larger memory for easy addition Comparatively more compact in memory
of elements size
Nested lists can be of variable size Nested arrays has to be of same size.
Can perform direct operations using Need to import proper modules to perform
functions like: these operations.
count()
sort()
max()
remove()
sum()
index()
append()
min()

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)

Output: array('i', [10, 20, 30, 40, 50])

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')

3. copy():The copy() method returns a copy of the specified array

Syntax: arrayname.copy()

Example :

import array as arr


PYTHON PROGRAMMING I YEAR/ I SEM MRCET
import copy

a=arr.array("i",[10,20,30,40,50])

b=arr.array("i")

b=copy.deepcopy(a)

print(b)

Output: array('i', [10, 20, 30, 40, 50])

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)

Output: array('i', [10, 20, 30, 40, 20, 50, 60])

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

Syntax :arrayname.insert(pos, elmnt)


Parameter Values:

Parameter Description

pos Required. A number specifying in which position to insert the value

elmnt Required. An element of any type (string, number, object etc.)

Example :
import array as arr

a=arr.array("i",[10,20,30,40])

a.insert(1,50)

print(a)

Output: array('i', [10, 50, 20, 30, 40])

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)

Output: array('i', [10, 20, 40])

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)

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

11.sort()
The sort() method sorts the list ascending by default.
You can also make a function to decide the sorting criteria(s).

Syntax : arrayname.sort(reverse=True|False, key=myFunc)


Parameter Values
Parameter Description

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:

import array as arr


l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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])

Elements sliced from 5th element till the end:


array('i', [6, 7, 8, 9, 10])

Printing all elements...


Searching Element in an Array
 In order to search an element in the array we use a python in-built index() method. This
function returns the index of the first occurrence of value mentioned in arguments.
Example:
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("The new created array is : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("The index of 1st occurrence of 2 is : ", end="")
print(arr.index(2))
print("The index of 1st occurrence of 1 is : ", end="")
print(arr.index(1))

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

You might also like