0% found this document useful (0 votes)
26 views12 pages

Arrays - Ipynb - Colaboratory

best book to learn arrays

Uploaded by

microsoftone26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views12 pages

Arrays - Ipynb - Colaboratory

best book to learn arrays

Uploaded by

microsoftone26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

18/11/2023, 19:12 Arrays.

ipynb - Colaboratory

Array
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).

Creating an Array
An Array in Python can be created by importing an array module. array(data_type, value_list) is used
to create an array with data type and value list specified in its arguments.

Basic Operations

Traverse − print all the array elements one by one.

Insertion − Adds an element at the given index.

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 1/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

Deletion − Deletes an element at the given index.

Search − Searches an element using the given index or by the value.

Update − Updates an element at the given index.

# Python program to demonstrate creation of an Array

# importing "array" for array creations


import array as arr

# creating an array with integer type


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

# printing original array


print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()

The new created array is : 1 2 3

# Python program to demonstrate adding elements to an Array

# importing "array" for array creations


import array as arr

# array with int type


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

print("Array before insertion : ", end=" ")


for i in range(0, 3):
print(a[i], end=" ")
print()

# inserting array using insert() function


a.insert(1, 4)

print("Array after insertion : ", end=" ")


for i in (a):
print(i, end=" ")
print()

Array before insertion : 1 2 3


Array after insertion : 1 4 2 3

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 2/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

# Python program to demonstrate accessing of element from an array

# importing array module


import array as arr

# array with int type


a = arr.array('i', [1, 2, 3, 4, 5, 6])

# accessing element of an array


print("Access element is: ", a[0])

# accessing element of an array


print("Access element is: ", a[3])

Access element is: 1


Access element is: 4

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 3/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

# Python program to demonstrate removal of elements in an Array

# importing "array" for array operations


import array

# initializing array with array values


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

# printing original array


print("The new created array is : ", end="")
for i in range(0, 5):
print(arr[i], end=" ")

print("\r")

# using pop() to remove element at 2nd position


print("The popped element is : ", end="")
print(arr.pop(2))

# printing array after popping


print("The array after popping is : ", end="")
for i in range(0, 4):
print(arr[i], end=" ")

print("\r")

# using remove() to remove 1st occurrence of 1


arr.remove(1)

# printing array after removing


print("The array after removing is : ", end="")
for i in range(0, 3):
print(arr[i], end=" ")

The new created array is : 1 2 3 1 5


The popped element is : 3
The array after popping is : 1 2 1 5
The array after removing is : 2 1 5

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 4/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

# Python code to demonstrate searching an element in an array

# importing array module


import array

# initializing array with array values


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

# printing original array


print("The new created array is : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")

print("\r")

# using index() to print index of 1st occurrence of 2


print("The index of 1st occurrence of 2 is : ", end="")
print(arr.index(2))

# using index() to print index of 1st occurrence of 1


print("The index of 1st occurrence of 1 is : ", end="")
print(arr.index(1))

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

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 5/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

# Python code to demonstrate how to update an element in an array

# importing array module


import array

# initializing array with array values


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

# printing original array


print("Array before updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")

print("\r")

# updating an element in an array


arr[2] = 6
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print()

# updating an element in an array


arr[4] = 8
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")

Array before updation : 1 2 3 1 2 5


Array after updation : 1 2 6 1 2 5
Array after updation : 1 2 6 1 8 5

NumPy
NumPy, which stands for Numerical Python, is a library consisting of multidimensional array
objects and a collection of routines for processing those arrays. It provides various computing tools
such as comprehensive mathematical functions, linear algebra routines.

pip install numpy

Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (1.23.5)

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 6/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

import numpy as np

# Creating array object


arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )

# Printing type of arr object


print("Array is of type: ", type(arr))

# Printing array dimensions (axes)


print("No. of dimensions: ", arr.ndim)

# Printing shape of array


print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array


print("Size of array: ", arr.size)

# Printing type of elements in array


print("Array stores elements of type: ", arr.dtype)

Array is of type: <class 'numpy.ndarray'>


No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64

You can create an array from a regular Python list or tuple using an array() function. The type of the
resulting array is deduced from the type of the elements in the sequences.

import numpy as np

# Creating array from list with type float


a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)

# Creating array from tuple


b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)

Array created using passed list:


[[1. 2. 4.]
[5. 8. 7.]]

Array created using passed tuple:


[1 3 2]

Often, the element is of an array is originally unknown, but its size is known. Hence, NumPy offers
several functions to create arrays with initial placeholder content. These minimize the necessity of

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 7/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

growing arrays, an expensive operation. For example: np.zeros, np.ones, np.full, np.empty, etc.

#Creating an array of zeros – using np.zeros()


arr = np.zeros((3,3))
arr

array([[0., 0., 0.],


[0., 0., 0.],
[0., 0., 0.]])

#Creating an array of ones – using np.ones()


arr = np.ones((3,3))
arr

array([[1., 1., 1.],


[1., 1., 1.],
[1., 1., 1.]])

#creating an array with constant value


arr = np.full((3,3),6)
arr

array([[6, 6, 6],
[6, 6, 6],
[6, 6, 6]])

#Creating a 2D array of random numbers


arr = np.random.random([3,2])
arr

array([[0.31860091, 0.17439734],
[0.26124141, 0.23708155],
[0.51282263, 0.72894495]])

arange: This function returns evenly spaced values within a given interval. Step size is specified.

#Creating an array within a given interval


arr = np.arange(0,1,5)
arr

array([0])

linspace: It returns evenly spaced values within a given interval.

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 8/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

#Creating an array of a given length


arr = np.linspace(0,1,5)
arr

array([0. , 0.25, 0.5 , 0.75, 1. ])

Reshaping array: We can use reshape method to reshape an array. The original size of the array
remains unchanged.

# Reshaping 3X4 array to 2X2X3 array


arr = np.array([[1, 2, 3, 4],
[5, 2, 4, 2],
[1, 2, 0, 1]])

newarr = arr.reshape(2, 2, 3)

print ("Original array:\n", arr)


print("---------------")
print ("Reshaped array:\n", newarr)

Original array:
[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
---------------
Reshaped array:
[[[1 2 3]
[4 5 2]]

[[4 2 1]
[2 0 1]]]

Flatten array: We can use flatten method to get a copy of the array collapsed into one dimension.

# Flatten array
arr = np.array([[1, 2, 3], [4, 5, 6]])
flat_arr = arr.flatten()

print ("Original array:\n", arr)


print ("Fattened array:\n", flat_arr)

Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 9/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

NumPy Array Indexing


Slicing: Just like lists in Python, NumPy arrays can be sliced. As arrays can be multidimensional,
you need to specify a slice for each dimension of the array.

Integer array indexing: In this method, lists are passed for indexing for each dimension. One-to-one
mapping of corresponding elements is done to construct a new arbitrary array.

Boolean array indexing: This method is used when we want to pick elements from an array which
satisfy some condition.

#Creating a 2D arrays
arr = np.array([[20,25,30,35], [40,50,60,70], [45,48,51,54]])

#Extracting specific rows and columns through slicing


print(arr[0:2,0:2])

#array with first 2 rows and alternate columns (0 and 2)


print(arr[:1, ::2])

#boolean array indexing


print(arr>0)

[[20 25]
[40 50]]
[[20 30]]
[[ True True True True]
[ True True True True]
[ True True True True]]

NumPy Basic Operations

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 10/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

# Python program to demonstrate basic operations on Single Array


import numpy as np

a = np.array([1, 2, 5, 3])

# add 1 to every element


print ("Adding 1 to every element:", a+1)

# subtract 3 from each element


print ("Subtracting 3 from each element:", a-3)

# multiply each element by 10


print ("Multiplying each element by 10:", a*10)

# square each element


print ("Squaring each element:", a**2)

# modify existing array


a *= 2
print ("Doubled each element of original array:", a)

# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])

print ("\nOriginal array:\n", a)


print ("Transpose of array:\n", a.T)

Adding 1 to every element: [2 3 6 4]


Subtracting 3 from each element: [-2 -1 2 0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1 4 25 9]
Doubled each element of original array: [ 2 4 10 6]

Original array:
[[1 2 3]
[3 4 5]
[9 6 0]]
Transpose of array:
[[1 3 9]
[2 4 6]
[3 5 0]]

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 11/12
18/11/2023, 19:12 Arrays.ipynb - Colaboratory

# Python program to demonstrate unary operators in numpy


import numpy as np

arr = np.array([[1, 5, 6],


[4, 7, 2],
[3, 1, 9]])

# maximum element of array


print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:", arr.max(axis = 1))

# minimum element of array


print ("Column-wise minimum elements:", arr.min(axis = 1))

# sum of array elements


print ("Sum of all array elements:", arr.sum())

https://colab.research.google.com/drive/1BEPz-PC6SKOv9U_0TJx7Xdp_yMCAQpgl#printMode=true 12/12

You might also like