✍️Introduction
An array is used to store multiple values in a single variable instead of creating separate variables for each value. Arrays help organize data efficiently and make it easier to perform operations on large sets of values.
In Python, arrays are mainly used when we want to store elements of the same data type and perform fast calculations.
Arrays are different from lists because arrays store only similar data types (like all integers or all floats), while lists can store mixed data types. Python provides arrays through the array module and also through libraries like NumPy for advanced operations.
Arrays are useful when:
-
Working with large amounts of numerical data
-
Performing calculations quickly
-
Saving memory compared to lists
-
Processing data in loops
Arrays are commonly used in scientific computing, data analysis, and real-world applications where efficient data storage and processing are required.
Are Arrays Available in Python?
Python does not have traditional built-in arrays like C or Java, but Python provides other ways to store multiple values in a single variable. These alternatives work like arrays and are commonly used in Python programs.
In Python, we can use the following instead of traditional arrays:
List : Most commonly used and flexible
-
array module : Stores same type of data
-
NumPy arrays : Used for advanced calculations
👉 In this article, we focus on Python array module for beginners.
Import Array Module :
Before using arrays in Python, we must import the array module.
The array module provides a way to store multiple values of the same data type in a single variable.
Python does not support arrays directly, so we use the array module to create and work with arrays.
import array # Imports the array module so we can create arraysNote:We must import the array module before creating an array in Python.
Create an Array in Python :
An array is a collection of elements of the same data type stored in a single variable.
In Python, arrays are created using the array module.
We must specify a typecode that tells Python what type of data the array will store (like integers or floats).
Arrays are more memory-efficient than lists when storing large numeric data.
Syntax:
array.array(typecode, elements)
- typecode → Defines data type (e.g.,
'i'for integers)
elements → Values stored in the array
Example:
import array as arr # Import array module and rename it as arr numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array with values print(numbers) # Print the arrayOutput:array('i', [10, 20, 30, 40])"Code executed successfully"Note:
✔ All elements in an array must be of the same data type. ✔
'i'typecode is used for integers.
Common Array Type Codes :
Each type code represents a specific data type like integer or float.
Using correct type codes ensures memory efficiency and faster processing.
| Type Code | Data Type |
|---|---|
| i | Integer |
| f | Float |
| d | Double |
| u | Unicode character |
Access Array Elements:
Accessing array elements means retrieving values from an array using their index position.
In Python arrays, indexing starts from 0.
The first element is at index 0, the second at 1, and so on.
We use square brackets [] to access elements.
Example:
import array as arr # Import the array module and give it a short name 'arr' numbers = arr.array('i', [10, 20, 30, 40]) # Create an array of integers with values 10, 20, 30, 40 print(numbers[0]) # Print the first element of the array (index starts at 0) print(numbers[2]) # Print the third element of the array (index 2)Output:10 30"Code executed successfully"Note:Index always starts from 0, sonumbers[0]is the first element.
Change Array Elements :
Changing array elements means updating the value of an existing element at a specific index in the array.
Arrays in Python are mutable, which means their values can be changed after creation.
-
We can modify an element by using its index number.
Indexing starts from 0, so the second element is at index 1.
Example:
import array as arr # Import the array module
numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array
numbers[1] = 25 # Change the element at index 1 (20 → 25)
print(numbers) # Print updated array
Output:array('i', [10, 25, 30, 40])
"Code executed successfully"
Note:We use array[index] = new_value to change an element in the array.Array Length :
Array length means the total number of elements present in an array.
In Python, we use the
len()function to find the number of elements in an array.-
It works with arrays, lists, strings, and other collections.
-
The length helps in loops and indexing operations.
Example:
import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array print(len(numbers)) # len() returns the total number of elementsOutput:4"Code executed successfully"Note:len(array_name)gives the total number of elements in the array.
Loop Through Array :
Looping through an array means accessing each element one by one using a loop.
In Python, we commonly use a
forloop to iterate through arrays.-
The loop automatically goes through each element in order.
-
It is useful for printing, searching, or processing array elements.
Example:
import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array for num in numbers: # Loop through each element in the array print(num) # Print the current elementOutput:10 20 30 40"Code executed successfully"Note:Theforloop automatically visits each element in the array one by one.
Add Elements to Array :
Adding elements to an array means inserting new values into the array after it has been created.
In Python arrays, we use the
append()method to add an element at the end of the array.-
The new element must match the array data type (type code).
-
For example, if the array type is integer (
'i'), only integers can be added.
Example:
import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array numbers.append(50) # Add 50 at the end of the array print(numbers) # Print updated arrayOutput:array('i', [10, 20, 30, 40, 50])"Code executed successfully"Note:append()always adds the element at the end of the array.
Remove Elements from Array :
Removing elements from an array means deleting values from the array when they are no longer needed.
Python arrays provide methods like
remove()andpop()to delete elements.-
remove(value)deletes a specific value from the array. -
pop()removes the last element from the array.
-
These operations help manage and update array data easily.
Example:
import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array numbers.remove(20) # Removes value 20 from the array numbers.pop() # Removes the last element (40) print(numbers) # Print updated arrayOutput:array('i', [10, 30])"Code executed successfully"Note:
remove()deletes a specific value.
pop()deletes the last element by default.If the value is not found,
remove()gives an error.
Array Index Method :
The index() method is used to find the position (index) of a specific element in an array.
Every element in an array has a position called an index.
-
Indexing starts from 0 in Python.
-
The
index()method returns the position of the first occurrence of the element.
-
If the element is not found, Python gives an error.
Example:
import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array print(numbers.index(30)) # Finds the index position of value 30Output:2"Code executed successfully"Explanation:
10 → index 0
20 → index 1
30 → index 2
40 → index 3
So the index of 30 is 2.
Note:
If the value does not exist:print(numbers.index(50))It will give an error:
ValueError: array.index(x): x not in array
Reverse an Array :
The reverse() method is used to reverse the order of elements in an array.
It changes the array in-place (original array is modified).
-
The first element becomes the last, and the last becomes the first.
-
It does not create a new array, it only rearranges elements.
Example:
import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array numbers.reverse() # Reverse the order of elements in the array print(numbers) # Print the reversed arrayOutput:array('i', [40, 30, 20, 10])"Code executed successfully"Explanation:
Before reverse:
10 → 20 → 30 → 40After reverse:
40 → 30 → 20 → 10Note:
reverse()permanently changes the original array.
Convert Array to List :
Python arrays and lists are different data structures.
-
Lists are more flexible and support many built-in methods.
-
We use the list() function to convert an array into a list.
-
After conversion, we can easily modify the data.
Example:
import array as arr # Import array module numbers = arr.array('i', [10, 20, 30]) # Create an integer array list_data = list(numbers) # Convert array into list print(list_data) # Print the listOutput:[10, 20, 30]"Code executed successfully"Note:After conversion, you can use list functions likeappend(),remove(), andsort().
Difference Between Array and List :
Arrays store elements of the same data type, while lists can store different data types.
Arrays are generally faster and use less memory, whereas lists are more flexible and commonly used in Python.
| Feature | Array | List |
|---|---|---|
| Data Type | Same type | Different types |
| Speed | Faster | Slower |
| Memory | Less | More |
| Usage | Numeric data | General purpose |
Real-Life Example :
This program stores student marks in an array and calculates the total marks.
import array as arr # Import array module marks = arr.array('i', [85, 90, 78, 88]) # Create an integer array of marks total = sum(marks) # Calculate total marks print("Total Marks:", total) # Print the total marksOutput:Total Marks: 341"Code executed successfully"Note:Arrays are commonly used in real-life applications like student result systems
and score calculations.
❌ Common Mistakes :
Forgetting to import array module
Using wrong type code
Adding different data type values
When to Use Arrays?
Mathematical calculations
Large numeric data
Performance-critical programs
Conclusion :
Python arrays are useful when you need fast and memory-efficient storage of same-type elements.
For most programs, lists are enough, but arrays are important to know.
💬 Quick Question :
What will be the output?
import array as arr
a = arr.array('i', [1, 2, 3])
a.append(4)
print(a)
Comment your answer 👇😊
📌 Related Articles
- Get link
- X
- Other Apps
Labels
Array- Get link
- X
- Other Apps
Comments
Post a Comment