In Python, Arrays are sequences that can hold elements of the same data type.
While Python does not have a built-in array data structure like some other programming languages (e.g., C, Java).
We can work with arrays using "lists" or the "array" module.
Lists are the most commonly used data structure in Python and can be used to represent arrays.
Lists can hold elements of different data types and can dynamically change in size.
your_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
The array module in Python provides a way to create arrays with elements of a single data type.
Arrays created using the array module are more memory-efficient than lists because they store only the raw array data.
import array your_array = array.array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9]) # 'i' indicates the data type (integer) print(your_array) # Output: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9]) print(type(your_array)) # Output: <class 'array.array'>
import array string_array = array.array('str', ["apple", "banana", "orange"])
We can create an "array" of "objects" using a "list", where each element of the list is an "object".
class Employee: def __init__(self, name, age): self.name = name self.age = age employee1 = Employee("Alice", 30) employee2 = Employee("Taylor", 28) employee_array = [employee1, employee2] for emp in employee_array: print(emp.name); # Output: Alice, Taylor
We can access elements of "arrays" (whether "lists" or "arrays" created with the array module) using "indexing" and "slicing".
import array your_array = array.array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9]) # 'i' indicates the data type (integer) print(your_array[0]) # Output: 1 print(your_array[0:2]) # Output: array('i', [1, 2])
Arrays (both lists and arrays created with the array module) support common operations like appending, removing, iterating, and more.
# Appending elements your_array.append(10) # Output: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # Removing elements your_array.remove(2) # Output: array('i', [1, 3, 4, 5, 6, 7, 8, 9, 10])
Use lists when we need a flexible, mutable collection of elements with different data types.
Use the array module when we need a memory-efficient collection of elements with the same data type and don't require dynamic resizing.
In most cases, lists are the preferred choice for working with arrays in Python due to their flexibility and ease of use.
However, if memory efficiency is a concern and we're working with large datasets of the same data type, the array module may be more suitable.