How to Create Arrays in Python?

In this tutorial, I will explain how to create arrays in Python. As a data scientist working on a project for a US-based company, I recently faced the need to efficiently store and manipulate large sets of data. That’s when I discovered the importance of arrays in Python. In this article, we will see various methods for creating arrays, along with practical examples.

Arrays in Python

Python array is a data structure that allows you to store multiple elements of the same data type in a contiguous block of memory. In Python, arrays are not a built-in data type, but they can be easily implemented using the array module or the popular NumPy library.

Read How to Find the Maximum Value in Python Using the max() Function

Create Arrays in Python

Python provides various ways to achieve this task, Let us see all important methods.

1. Use the Python array Module

Python’s built-in array module provides a way to create arrays of a specific data type. Here’s how you can create an array using the array module:

import array as arr

# Creating an integer array
int_array = arr.array('i', [1, 2, 3, 4, 5])
print(int_array)  

# Creating a character array
char_array = arr.array('u', ['J', 'o', 'h', 'n'])
print(char_array) 

Output:

array('i', [1, 2, 3, 4, 5])
array('u', 'John')

I have executed the above example code, you can refer to the screenshot below.

Create Arrays in Python

In the example above, we import the array module and use the array() function to create arrays. The first argument specifies the type code of the array, such as 'i' for integers and 'u' Unicode characters. The second argument is a list of initial values for the array.

Check out How to Find the Index of an Element in an Array in Python

2. Use NumPy

Python NumPy is a useful library for numerical computing in Python. It provides an efficient implementation of arrays called ndarray (n-dimensional array). Let’s see how to create arrays using NumPy:

import numpy as np

# Creating a 1D array
arr_1d = np.array([1, 2, 3, 4, 5])
print(arr_1d)  # Output: [1 2 3 4 5]

# Creating a 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)

Output:

[1 2 3 4 5]
[[1 2 3]
 [4 5 6]]
How to Create Arrays in Python

With NumPy, you can create arrays of various dimensions by passing nested lists to the array() function. NumPy arrays offer a wide range of functionalities and optimized performance for numerical computations.

Check out How to Check if an Array is Empty in Python

3. Use Specific Properties

NumPy provides several functions to create arrays with specific properties:

  1. zeros(): Creates an array filled with zeros.
zeros_array = np.zeros((3, 4))
print(zeros_array)

Output:

[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
  1. ones(): Creates an array filled with ones.
ones_array = np.ones((2, 2))
print(ones_array)

Output:

[[1. 1.]
 [1. 1.]]
  1. arange(): Creates an array with evenly spaced values within a given interval.
arange_array = np.arange(0, 10, 2)
print(arange_array) 

Output:

[0 2 4 6 8]
  1. linspace(): Creates an array with evenly spaced values over a specified interval.
linspace_array = np.linspace(0, 1, 5)
print(linspace_array)  

Output:

[0.   0.25 0.5  0.75 1.  ]

These functions provide convenient ways to create arrays with specific initial values or patterns.

Read How to Check the Length of an Array in Python

Examples

Let’s explore some real-world scenarios of using arrays in Python.

  1. Analyzing stock prices:
   import numpy as np

   # Stock prices of Apple, Google, and Microsoft
   stock_prices = np.array([150.23, 2415.85, 300.12])

   # Calculating the average stock price
   average_price = np.mean(stock_prices)
   print(f"The average stock price is: ${average_price:.2f}")
  1. Processing customer data:
   import array as arr

   # Customer IDs
   customer_ids = arr.array('i', [1001, 1002, 1003, 1004, 1005])

   # Checking if a customer exists
   target_customer = 1003
   if target_customer in customer_ids:
       print(f"Customer {target_customer} exists in the database.")
   else:
       print(f"Customer {target_customer} does not exist in the database.")
  1. Analyzing housing prices:
   import numpy as np

   # Housing prices in different cities
   housing_prices = np.array([[350000, 420000, 380000],  # New York
                              [450000, 500000, 480000],  # San Francisco
                              [300000, 320000, 310000]])  # Chicago

   # Calculating the average housing price in each city
   average_prices = np.mean(housing_prices, axis=1)
   print("Average housing prices:")
   print(f"New York: ${average_prices[0]:.2f}")
   print(f"San Francisco: ${average_prices[1]:.2f}")
   print(f"Chicago: ${average_prices[2]:.2f}")

These examples demonstrate how arrays can be used to store and analyze data in various domains, such as finance, customer management, and real estate.

Read How to Create a 2D Array in Python

Conclusion

In this tutorial, I helped you to learn how to create arrays in Python. I have explained what are arrays in Python and how to create arrays in Python. We discussed various methods like using Python array module, using NumPy, and using some specific properties. I showed a real-world example.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.