The Array data structure in Python is used to store the data in contiguous memory locations. Sounds similar to Lists? There are slight differences between Lists and Arrays in Python. This article covers Arrays in detail and different ways to initialize array in Python.
There is no built-in Array data type in Python.
We can either use
ndarray from the NumPy library or use
arrays module to work with Arrays. NumPy arrays are optimized to work with large data sets and are efficient to process numeric data.
How Array is different from List?
- Arrays support storing the items of the same data type but in Lists can have heterogeneous data types.
- Another major difference between Arrays and Lists is, List size is mutable which means you can alter the list size at a later point in time. Whereas in Arrays, we have to specify the size while creating it.
- Internally, List is implemented using the ‘Dynamic Array‘ concept that stores pointers in contiguous memory locations using which, it takes the advantage of dynamic resizing. Arrays are implemented using continuous memory blocks which are allocated while creating an Array and can’t be resized dymanically.
So, to summarize, Array can store a fixed collection of items, and Lists support dynamically changing the size of the list.
Dynamic Arrays concept allows you to store the data pointers in continuous memory locations. If we add new elements to a List, it will first check if there is enough space in the pointers array to accomodate new element reference. If so, it will store it.
Otherwise, it creates a new array of pointers with bigger size and copies the existing pointers to the new array and adds the new element reference at the contiguous location.
How to initialize array in Python?
Method 1: Using NumPy library
As mentioned earlier, there is no array in Python’s built-in data types. So to work with arrays, we can use the array from
Install the NumPy module to your python environment by executing this command in terminal. If you already have installed the NumPy, you can ignore this step.
pip3 install numpy
Here is the code to initialize numpy array in Python
#importing numpy library import numpy as np # create numpy array with specified values np_array = np.array([1,2,3,4,5,6]) print(np_array) #output: [1 2 3 4 5 6] # create numpy array with random numbers np_ramdon_array = np.random.random((5)) print(np_ramdon_array) #output: [0.98373321 0.79033451 0.66067606 0.98937705 0.74266533]
You can initiate an array either by using
numpy.array() method or you can declare it with some random values using
If you want to create a numpy array from an existing list, you can pass the list to
numpy.array() and it will convert it to array data type.
You can check the data type of the resultant array by using the below code.
type(np_array) #output: <class 'numpy.ndarray'>
Here are the other ways to create and declare arrays in Python with numpy module.
import numpy as np # create an array of size 5 with some junk values np_array = np.empty(5) print(np_array) #output: [0. 0.5 1. 1.5 2. ] # create array with zeros of specified size np_array = np.zeros(10, dtype = int) print(np_array) #output: [0 0 0 0 0 0 0 0 0 0] # create numpy array fills with all 1's np_array = np.ones(5, dtype = int) print(np_array) #output: [1 1 1 1 1] # create sequence array np_array = np.arange(10) print(np_array) #output: [0 1 2 3 4 5 6 7 8 9]
There are many other ways to initialize array in Python using NumPy. You can refer to the NumPy documentation for detailed emplaination about each function.
You can also create array in Python using the
array module. But they don’t give us the same level of flexibility as NumPy arrays.
Method 2: With array module
Python has an in-built
array module to work with arrays of numerical data. These arrays are similar to NumPy arrays but provide fewer functionalities to manipulate the data and work much slower compared to NumPy arrays.
Downside of array method
The one major downside of this method is, you can specify only the numerical arrays with this. It will not support strings.
Here is the code to declare an array in Python using
import array data = [1,3,5,7,9] #syntax to create an array of signed integers. data_array = array.array('i', data) print(data_array) #output: array('i', [1, 3, 5, 7, 9])
This method takes two parameters:
1.Type code: Typecode specifies the type of data. These typecodes are single-letter strings mapping to each data type. There are certain allowed values for this parameter.
You can list down all the allowed typecodes using the below code thread.
import array #printing all the allowed type codes. print(array.typecodes) #output: bBuhHiIlLqQfd
Here are the meanings of each one of these typecodes:
- b – signed integer
- B – unsigned integer
- u – unicode character
- h – unsigned short integer
- H – signed short integer
- i – signed integer
- I – unsigned integer
- l – signed long integer
- L – unsigned long integer
- q – signed long long integer
- Q – unsigned long long integer
- f – floating point
- d – double precision floating point
- g – long double floating point
- c – single precision complex
- d – double precision complex
- g – long double complex
Urgh! Pretty hard to type this big list. Similarly, it’s hard to remember which one to use for this parameter while declaring or initialize array in Python. All these type codes are available in
2. Data: The second parameter is of any iterable list you can pass to create an array.
We can use the functions like append(), pop() and insert() to work with data using this library.
Initialize Array with Specified Values
We can use
full() method in
numpy to create an array with a given shape and fill it with specified values.
full() method takes two arguments:
- shape of the array: You can specify the number of rows and columns of an array using a tuple of positive integers.
- constant value: This is used to fill the array with the constant value.
Here is an example of
full() method with different arguments.
import numpy as np #This creates one dimensional array of size 5 and fill-in with value 3 np_array = np.full((5), 3) print(np_array) #[3 3 3 3 3] # This will create an array with two rows and three columns and fill the data with constant 1 np_array = np.full((2,3), 1) print(np_array) '''[[1 1 1] [1 1 1]]'''
Initialize 2d array in Python:
We can create 2d array by passing multiple lists to the
numpy.array() method or alternatively, we can use
numpy.full() method to create a 2d array with specified value.
Here is the code to initialize a 2d array in Python.
import numpy as np # create two dimensional array np_array = np.array([[1,2,3], [4,5,6]]) print(np_array) '''[[1 2 3] [4 5 6]]''' # This will create a two dimensional array and fill the data with specified value '7' np_array = np.full((2,5), 7) print(np_array) '''[[7 7 7 7 7] [7 7 7 7 7]]'''
Best Practices to follow working with Arrays:
Both arrays and lists are super useful in day-to-day programming. Even though they both seem similar in most aspects, choosing the right data structure for your needs is quite important.
Keep in mind the following while working with Arrays:
- When you are working with large arrays, it is always a best practice to allocate the memory while initializing it rather than appending the items at a later point.
- Avoid using loops. Python loops are generally slower. Instead, you can opt for vectorized operations to run it faster and more memory-efficient.
numpylibrary while working with large data sets of numeric data. NumPy library provides highly optimized in-built functions for data processing and manipulation.
numpy.concatenate()instead of using
+operator to concatenate two arrays.
Hope we are able to help you with different ways to initialize array in Python. Follow codethreads.dev for more such insightful posts!!
Frequently Asked Questions
How do you initialize array in Python?
There are different ways to declare an array in Python.
1. Using NumPy arrays
2. Using array module
3. using List comprehension
Listed down all the methods with their code blocks.
How to initialize numpy array?
NumPy module provides easy ways to work with Arrays in Python. They provide a lot of flexible options to work with large data sets.
Here is the code to initialize numpy array.
How to initialize 2d array in Python?
We can use numpy module to work with 2d arrays. Here is the code for this.
Initialize 2d array in Python with NumPy