Junior — Middle
How can an array of data be declared and initialized in Python?
sobes.tech AI
Answer from AI
In Python, a data array is usually represented as a list. It can be declared and initialized in several ways:
# Empty list
arr = []
# List with elements
arr = [1, 2, 3, 4, 5]
# List with elements of different types
arr = [1, 'string', 3.14, True]
# Creating a list using a generator
arr = [x * 2 for x in range(5)] # [0, 2, 4, 6, 8]
If you need a structure with homogeneous types and a fixed size, you can use the array module:
import array
arr = array.array('i', [1, 2, 3, 4]) # array of integers
For scientific computations, numpy arrays are often used:
import numpy as np
arr = np.array([1, 2, 3, 4])