Arrays in Python
Python tutorial · PySpark.in
Arrays in Python
In Python, an array is a data structure that stores multiple values of the same data type in a single variable.
- Arrays are stored in contiguous memory locations, which makes them efficient for numerical operations.
- Python provides arrays using the array module (they are different from lists).
Importing array
Before using arrays, you must import them from the array module:
from array import array
Creating an Array
Each array needs:
- A type code (for example: 'i' for integer, 'f' for float)
- A list of values of that type
Accessing Array Elements
Array elements are accessed using indexing, just like lists (starting from index 0).
Slicing Arrays
You can extract a part of an array using slicing:
This returns elements from index 1 to 3 (end index is excluded).
Looping Through Arrays
You can iterate over array elements in two common ways:
Using a for loop(direct items)
Using indexing
Array Operations
Append an element at the end
Insert at a specific index
Remove an element by value
Extend array(add multiple elements)
Array Concatenation
You can combine two arrays of the same type using +:
Searching Elements
Use .index(value) to find the index of an element:
Array Methods
Method | Description | Example |
|---|---|---|
append(x) | Add item at end | arr.append(10) |
insert(i, x) | Insert item at index i | |
remove(x) | Remove first occurrence of x | arr.remove(3) |
pop(i) | Remove item at index i | arr.pop(2) |
extend(a2) | Add all elements from another array | arr.extend(a2) |
index(x) | arr.index(10) | |
reverse() | Reverse the array | arr.reverse() |
buffer_info() | Return memory address & length | arr.buffer_info() |
count(x) | Count occurrences of x | arr.count(2) |
Note
- Python does not have a true built-in array type like C/Java; instead, we use the array module when all items are of one data type.
- For numerical computing, most developers prefer NumPy arrays, which are faster and more powerful.
Example using NumPy:
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges