×

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

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Python sorted() function

Python sorted() function The sorted() function returns a sorted list of the specified iterable object. Syntax sorted(iterable, *, key=None, reverse=False) Parameter iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc. key:...

1 minute read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.

What does base case mean in recursion

Base cases and recursive stages are used to define recursive functions. In a primary subject, we compute the outcome right away, given the function call's arguments. In a recursive step, we...

4 minutes read.

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

How to create a file in Python?

How to create a file in python? Files provide us a convenient way of storing our information. Once we have our data, the next task is to store it so that...

3 minutes read.

Python Subprocess Call Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

StandardScaler in Sklearn

When and How Should You Use StandardScaler? StandardScaler comes into play whenever the properties of the provided dataset change significantly within their ranges or are recorded in different measurement units. Since using...

4 minutes read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.