Arrays store only elements of the same type, while lists can contain elements of different types.
In Python, arrays are collections of elements of the same type stored in contiguous memory locations. Using Python's array
module, you can perform various operations on arrays such as adding, updating, deleting elements, and more. Arrays offer a way to efficiently handle fixed data types, unlike lists which can hold different types of elements.
Imagine organizing a bookshelf by genre. In Python, arrays allow you to organize data similarly, grouping similar items in contiguous memory locations.
An array is a collection of elements of the same type that are stored at contiguous memory locations. Arrays are sequence types that behave very much like lists except that the type of objects stored in them is constrained. The idea is to store multiple items of the same type together.
We can treat lists like arrays; however, we cannot constrain the type of elements stored in a list.
Let's see a list example where elements are of the different types:
python_list = [2, 5.5, "Hai"]print (python_list)
Arrays in Python can be created by importing an array
module.
Array creation in Python follows the following syntax:
import array as ar
new_array = ar.array(data_type, value_list)
array(data_type, value_list)
is used to create an array with data type and value list specified in its arguments.
import array as arnew_arr = ar.array('d', [2, 5.5, "Hai"])print(new_arr)
The above code will throw an error since the elements in the array are of different data types.
Following are the different types of arrays in Python:
Datatype | Value |
---|---|
d | Represents floating-point of size 8 bytes |
b | Represents signed integer of size 1 byte |
i | Represents signed integer of size 2 bytes |
I | Represents unsigned integer of size 2 bytes |
B | Represents unsigned integer of size 1 byte |
c | Represents character of size 1 byte |
f | Represents floating-point of size 4 bytes |
Let’s now see a floating-point array example:
import array as arnew_arr = ar.array('d', [2.1, 4.5, 5.5])print(new_arr)
We can access each element of an array using the index of the element.
We can access a range of items in an array by using the slicing operator:
Python also has what you could call its "inverse index positions." Using this, you can read an array in reverse.
For example, if you use the index -1, you will be interacting with the last element in the array.
Knowing this, you can easily access each element of an array by using its index number.
For instance, if we wanted to access the number 16 in our array, all we need to do is use our variable (called with square brackets, []
) and the index position of the element.
Let's understand this with the help of an example. The below code shows how we can access elements.
import array as arnew_arr = ar.array('d', [2.1, 4.5,3.5,4.2,3.3, 5.5])print("First element:", new_arr[0])print("Second element:", new_arr[1])print("Last element:", new_arr[-1])print("Slicing array elements in a range: 3-5.\n", new_arr[2:5])print("Elements sliced from 3rd element to the end.\n",new_arr[3:])print("Printing all elements using slice operation.\n", new_arr[:])
Try experimenting with the code.
Here, consider altering the slicing indices in the example above to see different subsets of the array.
Let’s explore some different array operations such as finding the length of the array changing array elements, adding elements to an array etc.
Use the len()
method to return the length of an array (the number of elements in an array).
import array as arnew_arr = ar.array('b', [1,2,4,7,9,33])a = len(new_arr)print(a)
Arrays are mutable—their elements can be changed in a similar way as lists.
import array as arnew_arr = ar.array('i', [1, 2, 3, 5, 7, 10])new_arr[0] = 0print(new_arr)
Try updating any element with a character or a string and see how the code responds.
We can add one item to the array using the append()
method, or add several items using the extend()
method.
import array as arnew_arr = ar.array('i', [1, 2, 3])new_arr.append(4)print(new_arr)new_arr.extend([5, 6, 7])print(new_arr)
Below is an example where all different operations are being performed on the same array:
import array as arnew_arr = ar.array('i', [1, 2, 3])ln=len(new_arr)print(ln) #lengthnew_arr[0] = 0 #changing first elementprint(new_arr)new_arr.append(4) #appending 4 to arrayprint(new_arr)new_arr.extend([5, 6, 7]) #extending numbers with 5,6,7print(new_arr)
Insert operation is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of the built-in array.insert()
function in Python.
import array as arnew_arr = ar.array('i', [1, 2, 3, 5, 7, 10])new_arr.insert(1,9)for x in new_arr:print(x)
Deletion refers to removing an existing element from the array and re-organizing all elements of an array. The built-in remove()
method is there in Python.
import array as arnew_arr = ar.array('i', [1, 2, 3, 5, 7, 10])new_arr.remove(7)for x in new_arr:print(x)
Practice adding, updating, and removing elements in an array using Python's array
module.
Instructions
Create an array:
Initialize an array of integers with the following elements:
Add elements to the array:
Append the number
Insert the number
Update elements in the array:
Change the element at index
Modify the first element of the array to
Remove an element from the array:
Remove the element
Print the final array:
Display the final state of the array after all operations.
Initial array: array('i', [10, 20, 30, 40, 50])After appending 60: array('i', [10, 20, 30, 40, 50, 60])After inserting 25 at index 2: array('i', [10, 20, 25, 30, 40, 50, 60])After updating index 3 to 45: array('i', [10, 20, 25, 45, 40, 50, 60])After updating first element to 15: array('i', [15, 20, 25, 45, 40, 50, 60])After removing 30: array('i', [15, 20, 25, 45, 40, 60])Final array: array('i', [15, 20, 25, 45, 40, 60])
# Write your code here
You can refer to the given "Solution" on pressing the "Run" button if you are stuck.
Make sure to give it your best first!
To search an element in an array, there're are two methods:
Using the in
keyword
Using index()
method
in
keywordWe can use the in
keyword to check if an element exists in the array.
import array as army_array = ar.array('i', [10, 20, 30, 40, 50])# Check if an element existselement = 30if element in my_array:print(element, "found in the array.")else:print(element, "not found in the array.")
index()
methodWe can use the index()
method to get the index of the element in the array. If the element is not found, it raises a ValueError
.
import array as army_array = ar.array('i', [10, 20, 30, 40, 50])try:index = my_array.index(30)print("Element found at index", index)except ValueError:print("Element not found in the array.")
Take a minute and think what should be the output of the above code before clicking the "Run" button!
Also, try altering the code by changing the values to get a better understanding.
To reverse an array in Python we have several approaches. Here’s how we can reverse an array efficiently:
[::-1]
slicingWe can reverse an array using Python's slicing feature, which is simple and concise.
import array as arnew_arr = ar.array('i', [1, 2, 3, 2, 7, 10,2])# Reverse the array using slicingreversed_array = new_arr[::-1]print("Reversed array:", reversed_array)
reverse()
methodThe reverse()
method reverses the array in place.
import array as army_arr = ar.array('i', [1, 2, 3, 2, 7, 10,2])# Reverse the array in placemy_arr.reverse()print("Reversed array:", my_arr)
The count()
method is used to get the number of occurrences in the array.
array.count(x)
returns the number of occurrences ofx
in the array.
import array as arnew_arr = ar.array('i', [1, 2, 3, 2, 7, 10,2])occurrence_of_x = 2print(new_arr.count(occurrence_of_x))
Key takeaways
Arrays vs. lists: Arrays contain elements of a single type, while lists can hold elements of mixed types.
Array creation: Arrays in Python are created using the array
module with the syntax array(data_type, value_list)
.
Array operations: Python arrays support multiple operations such as accessing elements by index, slicing, appending, inserting, updating, and deleting elements.
Reversing an array: You can reverse an array in place using the reverse()
method or create a reversed copy using slicing ([::-1]
).
Array methods: Common methods include append()
, extend()
, insert()
, remove()
, count()
, and index()
for element operations.
Efficient storage: Arrays offer more efficient memory usage compared to lists when working with large data of the same type.
If you're eager to deepen your understanding of Python and sharpen your problem-solving skills, our Become a Python Developer path is the perfect next step. With this structured path, you'll go beyond fundamental concepts and dive into advanced topics that will prepare you for a successful career in software engineering.
Don’t just learn Python—become proficient and ready for the challenges of the real world.
Haven’t found what you were looking for? Contact Us