×

How to declare array in python

How to declare array in python?

Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used to specify the size of the array and then specify the elements it will hold.

The difference between an array and a list is that a list can hold multiple values of different data types whereas an array holds multiple values of the same data type.

In this article, we will discuss how we can declare an array in python.

Arrays and matrices have a special significance in the world of scientific calculations, image processing, and computer vision. The pixels of a picture are represented in the form of matrices for a better understanding of operations on the image.

Arrays can be declared in Python by importing the package numpy.

import numpy as np

Using numpy

The following program illustrates a simple way of declaring an array in python.

 import numpy as np   #importing the package
 x=np.array([1,2,3,4])  #array declaration
 print(x) #printing the array
 print(type(x))     #type of x
 print(x.ndim)     #dimension of array 

INPUT-

declare array in python

OUTPUT-

declare array in python

On executing the program, we can observe that the output it displays the elements of an array, the data type of our object 'x', and its dimension(it's 1 since it's linear).

A Two-dimensional array can be declared using the following program-

 import numpy as np   #importing the package
 x=np.array([[1,2,3,4],[5,6,7,8]])  #array declaration
 print(x) #printing the array
 print(type(x))     #type of x
 print(x.ndim)     #dimension of array 

INPUT-

declare array in python

OUTPUT-

declare array in python
 print(x) – Displays the array
print(type(x)) – Displays the type of object ‘x’
print(x.ndim) – Displays the dimension which is 2 in this case.

The elements of an array can be accessed using its index-

For example-

 import numpy as np   #importing the package
 x=np.array([[1,2,3,4],[5,6,7,8]])  #array declaration
 print(x[0][1]) #printing the array
 print(x[0][3])
 print(x[1][2])
 print(x[1][3]) 

INPUT-

declare array in python

OUTPUT-

declare array in python

USING RANGE():

The next method that we will use here to declare an array is a range().

Here we will use the range function and for loop for declaring our array.

The first step is to initialize it and then use it for loop and range together to add elements into it.

The following code illustrates how we can implement it-

 #array creation
 arr1=[]              #initialization
 for i in range(6):
     arr1.append(i)
 print(arr1)
 print(type(arr1)) 

INPUT-

declare array in python

OUTPUT-

declare array in python

USING ARANGE():

The next method of array declaration in Python that we will discuss is using the arange() function.

The syntax for arange() is:

np.arange(start = ,stop= ,step= ,dtype= )

start indicates the starting element of our array

stop indicates the last element of our array

step indicates the sequence or common difference between two consecutive elements.

dtype shows the type of elements we want to insert in our array.

Let us understand its working with the help of an example-

 import numpy as np
 arr=np.arange(1,10,1)  #array creation
 print(arr)             #displaying the array
 print(type(arr))       #displaying the type of array 

INPUT-

declare array in python

OUTPUT-

declare array in python

Using Typecodes & Initializers

In this approach of declaring the array we will specify a typecode and initialize the values of our array.

In this program, we will import the module array and use it for array creation-

 from array import *        #importing array module
 arr=('i',[1,2,3,4])        #array declaration
 for i in arr:
     print(i)               #printing the elements
 print(type(arr)) 

INPUT-

declare array in python

OUTPUT-

declare array in python

Type Codes that can be used while specifying an array-

  1. b-it represents the signed integer of the size 1 byte.
  2. B-it represents the unsigned integer of the size 1 byte.
  3. c-it represents the character of the size 1 byte.
  4. i-it represents the signed integer of the size 2 bytes.
  5. I-it represents the unsigned integer of the size 2 bytes.
  6. f-it represents the floating point of the size 4 bytes.
  7. d-it represents the floating point of the size 8 bytes.

Operations on array in python

The different operations that can be performed on an array in python are-

  1. Inserting an element in an array that can be done using arr.insert(position,value).
  2. Deletion operation that can be performed using arr.remove(value).
  3. Searching an element in an array using arr.index(value).
  4. Values in an array can be updated using arr[index]=new value.
  5. If we want to add a number to all the elements of an array we can simply write-
 import numpy as np
 x=np.array([1,2,3,4,5])
 print(x+1) 
  1. We can declare two arrays and perform all kind of arithmetic operations on them-
 import numpy as np
 x=np.array([1,2,3,4,5])
 y=np.array([6,7,8,9,10])
 print(x+y)
 print(x-y)
 print(x*2)
 print(y*4) 

Related Topics

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

IPython Display

A command shell, often known as IPython is a software application that makes an operating system's features accessible to users or other applications. Based on the purpose and specific functioning...

6 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

Python Key Error

What is an Error? Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called...

6 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.