introduction
Imagine you have a playlist of your favorite songs on your phone. This playlist is a list with each song arranged in a specific order. You can play the first song, skip to the second song, or jump to the fifth song. This playlist is much like an array in computer programming.
Arrays are one of the most basic and widely used data structures.
Essentially, an array is a structured way to store multiple items (such as numbers, characters, or other arrays) in a specific order, and if you know their position (index), you can can also be quickly accessed, modified, and deleted.
This guide provides a comprehensive overview of array data structures. First of all, let’s look at what an array is and what its main characteristics are. Next, we move into the world of Python and explore how arrays are implemented, manipulated, and applied in real-world scenarios.
Understand the array data structure
Arrays are one of the oldest and most basic data structures used in computer science and programming. Its simplicity and efficiency of certain operations make it an important topic for those who delve into the field of data management and operations.
An array is a collection of items, typically same typeis stored in contiguous memory locations.
This contiguous storage allows arrays to provide timely access to any indexed element. Each item in the array is called . elementthe position of an element within an array is defined by that element. index,Normally starting from zero.
For example, consider an array of integers. [10, 20, 30, 40, 50]
. Here, the elements are 20
I have an index of 1
:
There are multiple advantage How to use arrays to store data. For example, memory layout allows arrays to: ○(1) The (constant) time complexity of accessing an element by index. This is especially useful when random access to elements is required. Additionally, the array is stored in: contiguous memory locationsThis improves cache locality and can lead to improved overall performance for certain operations. Another notable advantage of using arrays is that once declared, arrays have a fixed size, making memory easier to manage and avoiding unexpected overflows and out-of-memory errors.
Note: Arrays are especially useful in scenarios such as the following: The size of the collection is known in advance and remains constantor when random accesses occur more frequently than insertions and deletions.
Arrays, on the other hand, come with their own set. Limitations. One of the main limitations of traditional arrays is that fixed size. Once an array is created, its size cannot be changed. This can lead to problems such as wasted memory (if the array is too large) or the need for resizing (if the array is too small). In addition to that, inserting or deleting an element in the middle of the array requires moving the element, so upon) The time complexity of these operations.
To wrap this all up, let’s use the song playlist example at the beginning of this guide to illustrate the main characteristics of arrays. An array is a data structure that looks like this:
-
Indexed: Just as each song in a playlist has a number (1, 2, 3,…), each element in an array has an index. However, in most programming languages, indexes start at 0. That is, the first item has index 0, the second item has index 1, and so on.
-
Fixed size available: For example, if you create a playlist with 10 songs, you cannot add the 11th song without first deleting one song. Similarly, arrays have a fixed size. Once you create an array of a certain size, you cannot add more items than its capacity.
-
homogeneous: All songs in the playlist are music tracks. Similarly, all elements in an array are of the same type. If you have an array of integers, you can’t suddenly store a text string there.
-
directly accessible: If you want to listen to the seventh song in the playlist, you can jump directly to that song. Similarly, with an array, you can access any element instantly if you know its index.
-
contiguous memory: This is a bit more technical. When an array is created in a computer’s memory, it occupies a contiguous block of memory. Think of it like rows of lockers next to each other at school. Each locker is next to each other with no gaps between them.
Python and arrays
Known for its flexibility and ease of use, Python provides multiple ways to work with arrays. Although Python does not have a native array data structure like other languages, it does offer a powerful alternative that works similarly and can even provide extended functionality.
At first glance, Python list Although they may seem synonymous with arrays, there are subtle differences and nuances to consider.
list | array |
---|---|
Built-in Python data structures | Not native in Python – comes from the `array` module |
dynamic size | Fixed (predefined) size |
Can hold items of various data types | Keep items of the same type |
Provide various built-in methods for operations | Need to import external module |
O(1) Time complexity of access operations | O(1) Time complexity of access operations |
consume more memory | Improving memory efficiency |
Looking at this table naturally raises the following questions: “When should I use which one?”. If you need a collection that can grow or shrink dynamically and can hold mixed data types, Python’s lists are the way to go. However, in scenarios where you need a more memory-efficient collection of elements of the same type, you may want to consider using Python. array
A module or an external library such as NumPy.
of array Python module
When most developers think of arrays in Python, they often think of lists by default. However, Python provides more specialized array structures through built-in functions. array
module. This module provides space-efficient storage of basic C-style data types in Python.
Python lists are very versatile and can store all kinds of objects, but they can be overkill, especially if you only need to store collections of basic data types such as integers or floating point numbers. there is.of array
The module provides a way to create arrays that are more memory efficient than lists of certain data types.
Creating an array
To use array
If it’s a module, you need to import it first.
from array import array
Once imported, you can create the array using: array()
constructor:
arr = array('i', [1, 2, 3, 4, 5])
print(arr)
here, 'i'
The argument indicates that the array contains signed data integer. Several other type codes are available. 'f'
float and 'd'
For doubles.
Accessing and modifying elements
You can access and modify elements in an array just as you would with a list.
print(arr[2])
Next, let’s modify the element by changing its value as follows: 6
:
arr[2] = 6
print(arr)
array method
of array
The module provides several methods for working with arrays.
-
append()
– Adds an element to the end of the array.arr.append(7) print(arr)
-
extend()
– Add repeatable elements to the end.arr.extend([8, 9]) print(arr)
-
pop()
– Removes and returns the element at the specified position.arr.pop(2) print(arr)
-
remove()
: Removes the first occurrence of the specified value:arr.remove(2) print(arr)
-
reverse()
: Reverse the order of the array.arr.reverse() print(arr)
Note: There are many other methods than those listed here. To see a list of all methods available in Python, see the official Python documentation. array
module.
on the other hand, array
Modules provide a more memory efficient way to store basic data types. It’s important to remember that module. Limitations.Unlike lists, arrays homogeneous. This means that all elements in the array must be of the same type. Also, it can only be stored. Basic C-style data types In an array. If you need to store custom objects or other Python types, you should use a list or another data structure.
NumPy array
NumPy (short for Numerical Python) is a foundational package for numerical computation in Python. One of its main features is its powerful functionality. N-dimensional array objectprovides fast operations on arrays, including mathematical, logical, shape operations, etc.
NumPy arrays are more versatile than Python’s built-in arrays
array
It is a module and a staple of data science and machine learning projects.
Why use NumPy arrays?
The first thing that comes to mind is performance. NumPy arrays are implemented in C and benefit from optimized algorithms and contiguous memory storage for efficient memory storage and fast operations.
Python’s built-in lists and arrays are one-dimensional, whereas NumPy arrays are multidimensionalperfect for representing matrices and tensors.
Find a practical, hands-on guide to learning Git that includes best practices, industry-recognized standards, and cheat sheets. Stop Googling Git Commands and Actually learn that!
Finally, NumPy is huge functionality Manipulate these arrays from basic arithmetic to advanced math operations, reshaping, splitting, and more.
Note: If you know the size of your data in advance, preallocating memory for arrays (especially in NumPy) can lead to performance improvements.
Creating a NumPy array
To use NumPy, you must first install it (pip install numpy
) and import it.
import numpy as np
Once imported, you can create a NumPy array using: array()
function:
arr = np.array([1, 2, 3, 4, 5])
print(arr)
You can also create multidimensional arrays.
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix)
This gives you:
[[1 2 3]
[4 5 6]
[7 8 9]]
In addition to these basic ways to create arrays, NumPy provides other clever ways to create arrays. One of them is arange()
Method. Create an array whose values increase periodically.
arr = np.arange(10)
print(arr)
the other one is, linspace()
This method creates an array with the specified number of elements spaced evenly between the specified start and end values.
even_space = np.linspace(0, 1, 5)
print(even_space)
Accessing and modifying elements
Accessing and modifying elements in NumPy arrays is intuitive.
print(arr[2])
arr[2] = 6
print(arr)
We do much the same thing for multidimensional arrays.
print(matrix[1, 2])
matrix[1, 2] = 10
print(matrix)
Change the value of the second row element (index). 1
) and the third column (index 2
):
[[1 2 3]
[4 5 20]
[7 8 9]]
Changing the shape of an array
NumPy provides many functions and methods for manipulating and manipulating arrays. For example, you can use: reshape()
how to Change the shape of an array. Suppose we have a simple array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print("Original Array:")
print(arr)
And I would like to reshape it into a 3×4 matrix. all you have to do is reshape()
Methods passing the required dimensions as arguments:
reshaped_arr = arr.reshape(3, 4)
print("Reshaped Array (3x4):")
print(reshaped_arr)
This will give you a result like this:
Reshaped Array (3x4):
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
matrix multiplication
of numpy.dot()
The method is used matrix multiplication. Returns the dot product of two arrays. For a one-dimensional array, internal products of an array. For a two-dimensional array, this is equivalent to: matrix multiplicationfor ND, Wasumi It runs across the last axis of the first array and the penultimate axis of the second array.
Let’s see how it works. First, let’s calculate the dot product (dot product of vectors) of two one-dimensional arrays.
import numpy as np
vec1 = np.array([1, 2, 3])
vec2 = np.array([4, 5, 6])
dot_product_1d = np.dot(vec1, vec2)
print("Dot product of two 1-D arrays:")
print(dot_product_1d)
This will give you a result like this:
Dot product of two 1-D arrays:
32
32
In fact, this is the dot product of two arrays – (14+25 + 3*6). Next, you can perform matrix multiplication of two two-dimensional arrays.
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.array([[2, 0], [1, 3]])
matrix_product = np.dot(mat1, mat2)
print("Matrix multiplication of two 2-D arrays:")
print(matrix_product)
This gives you:
Matrix multiplication of two 2-D arrays:
[[ 4 6]
[10 12]]
NumPy arrays are a huge step up from Python’s built-in lists. array
Especially modules for scientific and mathematical calculations. The rich functionality provided by the NumPy library and its efficiency make it an essential tool for anyone who wants to perform numerical operations in Python.
conclusion
A cornerstone of computer science and programming, arrays have proven their value time and time again across a variety of applications and domains. In Python, this basic data structure is expressed through various instantiations such as lists, array
Modules and powerful NumPy arrays provide developers with a blend of efficiency, versatility, and simplicity.
This guide has covered the basic concepts of arrays to practical applications in Python. We’ve seen how the contiguous nature of arrays in memory reduces access times, and how Python’s dynamic lists provide a layer of flexibility. We also delved into the special world of NumPy, which turns arrays into powerful tools for numerical computation.