Open In App

Declaring an Array in Python

Last Updated : 10 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Declaring an array in Python means creating a structure to store multiple values, usually of the same type, in a single variable. For example, if we need to store five numbers like 10, 20, 30, 40, and 50, instead of using separate variables for each, we can group them together in one array. Let's understand different methods to do this efficiently.

Using Python list

Python lists are the most commonly used way to store multiple values. Although not a true array, a list can function like one and even hold mixed data types. However, when used as arrays, it's recommended to keep the data type consistent.

Python
a = [12, 34, 45, 32, 54]

for i in range(len(a)):
    print(a[i], end=" ")
a[0] = 100
a.append(99)

print("\nModified array:")
print(a)

Output
12 34 45 32 54 
Modified array:
[100, 34, 45, 32, 54, 99]

Explanation: [] creates a list (array-like) in Python. Elements are accessed using a[i] and modified with a[i] = value. Lists are mutable and append() adds elements at the end.

Using array Module

The array module allows you to create actual arrays with type constraints, meaning all elements must be of the same type (e.g., integers or floats). This makes them more memory-efficient than lists for large numeric datasets.

Python
import array as arr
a = arr.array('i', [10, 20, 30, 40, 50])

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

Output
10 20 30 40 50 

Explanation: array() from the array module creates a typed array in Python. 'i' denotes integer type. It's memory-efficient for numeric data but limited to primitive types.

Using Numpy

NumPy is a powerful third-party library used in data science and scientific computing. It supports multi-dimensional arrays (1D, 2D, 3D, etc.) and allows efficient mathematical operations.

Python
import numpy as np

a = np.array([10, 23, 34, 33, 45])
print("1D Array:")
print(a)

b = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(b)

c = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:")
print(c)

Output
1D Array:
[10 23 34 33 45]

2D Array:
[[1 2 3]
 [4 5 6]]

3D Array:
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

Explanation: np.array() creates arrays of various dimensions. A 1D array stores a simple list, a 2D array represents a matrix and a 3D array holds data in three dimensions.

Using list comprehension

List comprehension is a concise way to create lists (or array-like structures) in Python using a single line of code. It's particularly useful when you need to generate arrays dynamically.

Python
a = [x**2 for x in range(1, 11)]
print(a)

Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Explanation: [x**2 for x in range(1, 11)] generates squares of numbers from 1 to 10. x**2 computes the square and range(1, 11) gives numbers 1 to 10.

Related articles


Article Tags :
Practice Tags :

Similar Reads