In Python, arrays are very useful as they allow us to store multiple values in a single variable. They are incredibly versatile and have many applications. This tutorial will guide you through the process of creating an array in Python.
Step 1: Understanding the two types of arrays in Python
There are two main types of arrays in Python:
1. Lists: Lists are the most commonly used arrays in Python, as they can store different data types (such as integers, strings, and other objects) and dynamically adapt to changes in size. They are part of Python’s built-in features.
2. Arrays (from the array
module): These are the traditional arrays that can only store a single data type, such as integers or floating-point numbers, and have a fixed size once created. These are useful when dealing with large amounts of numerical data and provide better performance compared to lists.
In this tutorial, we will cover how to create both types of arrays in Python.
Step 2: Create a list
Creating a list in Python is very simple. You just use square brackets []
and separate the elements inside with commas ,
.
Here’s an example code to create a list containing integers and a string:
1 2 |
my_list = [1, 2, 3, 'Hello World'] print(my_list) |
Step 3: Creating an array with the array
module
To create an array with the array
module, you first need to import the module with the following command:
1 |
import array |
After that, you can create an array using the array.array()
function, which takes two arguments: the type code (which indicates the data type of the elements) and the list of elements. Here’s an example:
1 2 3 4 |
import array my_array = array.array('i', [1, 2, 3, 4, 5]) print(my_array) |
In the above example, 'i'
is the type code for integers. Different type codes are used for other data types (such as 'f'
for floating-point numbers). You can find more information about type codes in the Python documentation.
Full code
1 2 3 4 5 6 7 |
my_list = [1, 2, 3, 'Hello World'] print(my_list) import array my_array = array.array('i', [1, 2, 3, 4, 5]) print(my_array) |
Output
[1, 2, 3, 'Hello World'] array('i', [1, 2, 3, 4, 5])
Conclusion
In this tutorial, you’ve learned how to create an array in Python, either as a list or using the array
module. Both methods have their advantages and are useful in different situations.