Arrays in python

              An array is a basic data structure that can be implemented easily. The data is stored is of same data type.

Let us implement the array in python. It can be done by three ways listed as follows….

  • ·       Using array module
  • ·       Using Lists
  • ·       Using NumPy arrays

Let us create the coding samples in python.

Using ‘array’ module:

 This method is useful for homogeneous data. It is memory-efficient and easy to implement.

  • ·       First import the array module.
  • ·       An integer array  is created with elements.
  • ·       Using ‘append’ function, add the data.
  • ·       Using ‘remove’ function, you can able to delete the data.
  • ·       Finally,display the data in the array.

Python Code:

import array

# Create an integer array

sample_array = array.array('i', [10, 22, 13, 94, 65,76])

# Append and remove

sample_array.append(103)

sample_array.remove(65)

print(sample_array)

Output:

10 22 13 94 76 103

Using Lists:

              Let us create a list for accessing array elements. Here, you can create a list for array, access the elements, modify the elements and iterate the elements.

Python code:

import array

# Creating a list for array

sample_array = [23, 34, 45, 56, 65, 76]

# Accessing elements

print(sample_array[1])  

print(sample_array[3]) 

# Modify the elements

sample_array[1] = 27

print(sample_array)      # [10, 25, 30, 40]

# Iteration

for y in sample_array:

    print(y)

Output:

34

56

[23, 27, 45, 56, 65, 76]

23

27

45

56

65

76

Using Numpy:

              This is useful in implementing AI, Machine learning algorithms.

First, import the numpy builtin module.

Create an object for numpy.

Print the size and shape of the array.

Finally,vectorized operations are done and output is displayed.

Python Code:

import numpy as np1

# Let us Create a NumPy array

s_arr = np1.array([11, 22, 33, 44, 55, 66, 77])

# let us print the shape and size

print(s_arr.shape)  

print(s_arr.size)   

# Vectorized operations

print(s_arr * 2) 

output:

(7,)

7

[ 22  44  66  88 110 132 154]

These are the methods to implement array in python in various ways. Hope, this blog is useful to you. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Datatypes and Variables in java script