How to Initialize an Array in Python

How to Initialize an Array in Python

Last Updated: June 24, 2024By

This post will elaborate on Initializing an array in Python.

How to initialize an array in Python

Unlike other languages, Arrays in Python can be initialised differently depending on the array type. They are list, array module and NumPy arrays. We will discuss them in detail:

Initializing a List

Lists in Python can be initialized directly with values or dynamically:

Example code:

Initializing a list with values
my_list = [6,5,4,3,2]

Initializing an empty list
empty_list = []

Initializing a list with repeated values
repeated_list = [0] * 5

Output: [0, 0, 0, 0, 0]

Using list comprehension
squared_list = [i**2 for i in range(5)]

Output: [36,25,16,9,4]

Initializing an Array using the array Module

The array module can be used to create arrays that are more memory efficient than lists:

Example code:

import array as arr

** Initializing an array with values
my_array = arr.array(‘i’, [6,5,4,3,2])

**Initializing an empty array of integers
empty_array = arr.array(‘i’)

**Initializing an array with repeated values
repeated_array = arr.array(‘i’, [0] * 5) # Output: array(‘i’, [0, 0, 0, 0, 0])

print(my_array)
print(empty_array)
print(repeated_array)

There are many other type code that you can refer in this table below

Initializing a NumPy Array

NumPy provides powerful array creation and manipulation capabilities, making it ideal for numerical computations:

Example code:

import numpy as np

** Initializing a NumPy array with values
my_array = np.array([1, 2, 3, 4, 5])

**Initializing an empty NumPy array with a given shape
empty_array = np.empty(5) # Creates an uninitialized array of length 5

** Initializing a NumPy array with zeros
zeros_array = np.zeros(5) # Output: array([0., 0., 0., 0., 0.])

**Initializing a NumPy array with ones
ones_array = np.ones(5) # Output: array([1., 1., 1., 1., 1.])

**Initializing a NumPy array with a range of values
range_array = np.arange(5) # Output: array([0, 1, 2, 3, 4])

**Initializing a NumPy array with random values
random_array = np.random.rand(5) # Output: array with 5 random values between 0 and 1

print(my_array)
print(empty_array)
print(zeros_array)
print(ones_array)
print(range_array)
print(random_array)

NumPy Arrays are Ideal for numerical and scientific computations, offering a wide range of array operations and better performance for large datasets.

editor's pick

latest video

news via inbox

Nulla turp dis cursus. Integer liberos  euismod pretium faucibua

Leave A Comment