Arrays and Array Creation:

The “array” module in Python provides a way to store and manipulate collections of data that share a common data type, these collections are known as Python arrays. By using the “array” module, Python programmers can manipulate arrays, including functions for sorting, searching, and modifying array data. Python arrays are used when you need to use many variables which are of the same type. 

The basic operations that are supported by an array are:

1)Traverse − print all the array elements one by one

2)Insertion − Adds an element at the given index.

3)Deletion − Deletes an element at the given index.

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

5)Update − Updates an element at the given index.

To create a NumPy array, you can use the `np.array()` function. This function takes a Python list or tuple as input and returns a NumPy array. For example, the following code creates a 1-dimensional array of integers:

Example –  

import numpy as np
my_array = np.array([1,2,3,4,5])

Output –

         [1,2,3,4,5]  

You can also create multi-dimensional arrays using nested lists. For example the following code creates a 2-dimensional array:

import numpy as np

my_array=np.array([1,2,3],[10,11,12])

print(my_array)

Output – 

            [[1,2,3]

              [4,5,6]]

NumPy also provides several functions for creating arrays with specific values

For example -> np.zeros() – This function returns a new array of given shape and type, with zeros.

Here is an example

import numpy as np
my_array = np.zeros(5)

Output – 

             [0. 0. 0. 0. 0.]

np.ones() – This function returns a new array of given shape and type, with ones.

Here is an example

import numpy as np
my_array = np.ones(5)

Output – 

            [1. 1. 1. 1. 1.]

In addition to these basic array creation functions, NumPy also provides more advanced functions for creating arrays 

For example ->

np.arange([start],[stop],[step]) – this function returns evenly spaced values within a given interval. By default start values is 0 and the step value is 1

Here is an example for better understanding

import numpy as np
a = np.arange(5,9)

print(a)

Output –  [5 6 7 8]

The np.linspace() function returns number spaces evenly with respect to the interval. Similar to arange but instead of step it uses a sample number.

For example –

np.linspace(3.0, 4.0, num=5)

Output –   array([3.  , 3.25, 3.5 , 3.75, 4.  ])

The numpy.random.rand() function creates an array of a given shape and generates random values between 0 to 1.

For example –

import numpy as np
array = np.random.rand(5)
print(array)

Output – 

[0.8957591  0.58208362 0.50073592 0.76192711 0.42308067]

Run Code In Live & Test

Leave a Reply

Your email address will not be published. Required fields are marked *