Log In

How to Create an Array in Python

How to Create an Array in Python
23.11.2023
Reading time: 7 min
Hostman Team
Technical writer

There are no classic arrays in Python by default: their functions are performed by lists. However, if necessary, the array creation function can be called. Therefore, to say that there are no arrays in Python is not entirely correct; they are still there, but you need to import a specific function to use them

Lists and arrays

The main difference between the two is that lists can store heterogeneous data, while arrays can only store data of the same type. For example, only strings or only numbers, and integers and floating-point numbers would be stored separately. 

So, this list in Python:

list = ['element1', 'element2', 'element3']

simultaneously performs the functions of an array. As you can see, the list elements are located inside square brackets and separated by commas. 

Here we took strings as an example. Let's look at another example:

>>> different = ['55', 'string', '32.5', ['list_in_list', '55', 'string', '32.5']]
>>> print(different)

['55', 'string', '32.5', ['list_in_list', '55', 'string', '32.5']]

This is also a list with array functions since all the elements here are formatted as strings. Now let's write the following:

>>> different2 = [55, 'string', 32.5, ['list_in_list', '55', 'string', '32*8']]
>>> print(different2)

[55, 'string', 32.5, ['list_in_list', '55', 'string', '32*8']]

Such a list is no longer a classic array since it combines heterogeneous elements: an integer, a string, a floating point number, and a list. So it turns out that lists include array functions, but their own functions are wider.

This is where the logical question arises: Why call a separate module to create arrays when you can use lists that include both functions? There is only one, but a good reason for this: called arrays are more compact and consume less memory. It is useful when working with resource-intensive applications and performing low-level operations.

Working with arrays

Further, we will not consider the classic lists but focus on working with called arrays. To import them, we should use the array module. Important note: The array function only allows you to create arrays from integer and floating-point values. Unicode characters are also supported for the time being, but starting with version 4.0, Python will no longer support Unicode. 

So, let's focus on int and float values.

Import array module 

So, the array function makes arrays available in a Python program. While it can be called using different methods, this one seems the most convenient, as it minimizes the number of subsequent errors:

from array import *

Of course, this command, like other general instructions, must be indicated in the "header" of the code, that is, at the very top.

Creating an array

To create an array, use the following pattern:

array_name = array(typecode,[ ])

Let's look at each element of the array in more detail:

  • array_name is the name (you can set any name that adheres to the rules for creating variables in Python);

  • array is the actual function;

  • typecode is the type of stored data (usually i for integer values, d for floating-point numbers);

  • inside the [ ] brackets you should list the array elements, separated by commas.

Now let's try to create a simple array:

>>> from array import *
>>> integers = array('i',[1,2,3,4,5])
>>> print(integers)

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

Okay, it works. Let's create an array with floating point numbers:

>>> from array import *
>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> print(floats)

array('d', [3.5, 7.2, 5.3, 9.5, 4.0])

But what happens if we replace the integer with a floating point number in the first example?

>>> integers = array('i',[1,2,3,4,5.2])

Traceback (most recent call last):
 File "<pyshell#26>", line 1, in <module>
   integers = array('i',[1,2,3,4,5.2])
TypeError: integer argument expected, got float

As expected, we receive an error; the interpreter expects an integer argument. 

Let’s use a different typecode:

>>> floats = array('d',[3.5,7.2,5.3,9.5,4])
>>> print(floats)

array('d', [3.5, 7.2, 5.3, 9.5, 4.0])

Here, we presented the last number as an integer, but no error occurred: the interpreter managed to convert it to the desired form in the output.

Array operations

You can perform various operations on arrays, just like on lists.

  • The len() function allows you to count the number of elements:

>>> integers = array('i',[1,2,3,4,5])
>>> print(len(integers))

5
  • You can also index the elements and display the ones you need (for this, use the print(array[number]) construct):

>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> print(floats[0])

3.5

>>> print(floats[4])

4.0

>>> print(floats[1])

7.2

Note that numbering in Python always starts at zero, so to call the first element, we type print(floats[0]). Accordingly, the fifth element is number 4. And what happens if you try to call an element outside the array?

>>> print(floats[5])

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    print(floats[5])
IndexError: array index out of range

The interpreter gives an error message informing us that the index is out of range. 

Sometimes, negative indexing may be required. In this case, the countdown starts from the last element, which gets index -1:

>>> print(floats[-1])

4.0

>>> print(floats[-2])

9.5

>>> print(floats[-5])

3.5

Module 5 works correctly with negative indexing since the numbering does not start from zero.

  • Loop operations are also available. This is how a sequence of elements is displayed using a for loop:

>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> for d in floats:
print(d)

3.5
7.2
5.3
9.5
4.0
  • Unlike strings, you can change arrays and lists in Python, so the following operations are also allowed:

>>> floats[1] = 8.2
>>> print(floats)

array('d', [3.5, 8.2, 5.3, 9.5, 4.0])

The value of the second element was 7.2, but we assigned a new one - 8.2.

  • If the values of the elements change, can we add a new element? To do this, use the append() method.

>>> integers = array('i',[1,2,3,4,5])
>>> integers.append(6)
>>> print(integers)

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

The main thing is that the added element should be of the same data type as those already in the array, otherwise, the interpreter will give an error:

>>> integers.append(7.0)

Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
    integers.append(7.0)
TypeError: integer argument expected, got float
 

The error type indicates we entered a floating point number instead of the expected integer value. It is possible to convert the entered integer to a floating point number but it is not entirely correct to do so:

>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> floats.append(8)
>>> print(floats)

array('d', [3.5, 7.2, 5.3, 9.5, 4.0, 8.0])
  • The extend() method will help you add multiple elements to an array. Enter this in the interpreter:

>>> floats.extend([4.5,5.7,6.9])
>>> print(floats)

array('d', [3.5, 7.2, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])
  • And what if we need to insert a new element at some specific position? This is what the insert() method is for, and here's how to use it (we use the same modified array with floats from the example above):

>>> floats.insert(1,2.3)
>>> print(floats)

array('d', [3.5, 2.3, 7.2, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])

We inserted the number 2.3 in the second position (remember the numbering starts from zero, so the second position will be number 1).

  • Since you can add and insert elements, there must be a method for removing them. It's called remove():

>>> floats.remove(7.2)
>>> print(floats)

array('d', [3.5, 2.3, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])

And here's what happens if there are several elements in the array with the same value:

>>> integers = array('i',[11,12,13,14,15,11,11])
>>> integers.remove(11)
>>> print(integers)

array('i', [12, 13, 14, 15, 11, 11])
 

Only the first value, 11, was removed, while the rest remained in the array. To remove an element at a specific position, use the pop() method:

>>> integers = array('i',[11,12,13,14,15,11,11])
>>> integers.pop(5)

11

>>> print(integers)

array('i', [11, 12, 13, 14, 15, 11])

We have successfully removed the number 11 in the sixth position from the array.

Conclusion

Today, we learned about arrays in Python: how to create them and perform various operations. We also learned the advantages of called arrays over standard lists, which often perform the functions of both of these structures in Python.


Share