Notes on my journey learning to code with Python & Django
AMartin1987 | Published on: Dec. 27, 2023, 8:48 p.m.
An array is a linear data structure that stores a collection of similar data types at continuous locations in a computer's memory.
An representation of an array in memory. Source: GeekForGeeks
Like arrays, lists are also data structures used to store multiple items.
Quoting the excellent LearnPython article, both arrays and lists in Python share some traits:
Example of a list in Python:
list = [3, 6, 9, 12]
print(list)
print(type(list))
Result:
[3, 6, 9, 12]
<class 'list'>
However, lists are different from arrays in that their elements can always be of different data types: you can combine strings, integers, and objects in the same list. In contrast, when it comes to the array's ability to store different data types, it depends on the kind of array used.
To use arrays in Python, you need to import either an array module or a NumPy package.
import array as arr
import numpy as np
The Python array module requires all array elements to be of the same type. Moreover, to create an array, you'll need to specify a value type. In the code below, the "i" signifies that all elements in array_1 are integers:
array_1 = arr.array("i", [3, 6, 9, 12])
print(array_1)
print(type(array_1))
Result:
array('i', [3, 6, 9, 12])
<class 'array.array'>
On the other hand, NumPy arrays support different data types. To create a NumPy array, you only need to specify the items (enclosed in square brackets):
array_2 = np.array(["numbers", 3, 6, 9, 12])
print (array_2)
print(type(array_2))
Result:
['numbers' '3' '6' '9' '12']
<class 'numpy.ndarray'>
As you can see, array_2 contains one item of the string type (i.e., "numbers") and four integers.
Moreover, arrays are different from lists in that:
My name is Alejandra and I'm learning Python & Django to become a backend developer. I also love videogames, anime, plants and decorating my home.
You can contact me at alejandramartin@outlook.com
You can also visit my portfolio.