Array
In Python, an array is a collection of elements, each identified by an index or a key. The most basic type of array-like structure in Python is a list, which can be defined using square brackets. Lists in Python can hold a mix of data types and can be resized dynamically. Here's an example of a list in Python:
my_list = [1, 2, 3, 4, 5]
Python also has a module named array which can be used to create arrays with elements of the same type, which is more memory efficient than lists for large collections of data. Here’s an example using the array module:
import array
my_array = array.array('i', [1, 2, 3, 4, 5]) # 'i' denotes that the elements are of type signed int.
Accessing Elements
You can access elements of an array or a list using indexing. For example:
print(my_list[0]) # prints 1
print(my_array[1]) # prints 2
Modifying Elements
You can modify elements of an array or list by assigning a new value to the corresponding index:
my_list[0] = 10
my_array[1] = 20
Adding Elements
You can add elements to a list using methods like append or extend:
my_list.append(6)
For adding elements to an array.array, you can use the append method or the extend method if you want to add multiple elements:
my_array.append(6)
Removing Elements
You can remove elements from a list using methods like remove or pop:
my_list.remove(10) # removes the element 10 from the list
my_list.pop(1) # removes the element at index 1
For an array.array, you can use similar methods:
my_array.remove(20)
my_array.pop(1)
Iterating over Elements
You can iterate over the elements of an array or a list using a for loop:
for item in my_list:
print(item)
for item in my_array:
print(item)
Slicing
You can use slicing to access a subset of elements in a list or an array:
print(my_list[1:4]) # prints elements from index 1 to index 3
print(my_array[2:5]) # prints elements from index 2 to index 4
Additional Data Structures
In addition to lists and the array module, Python also has more advanced data structures like:
- Tuples: Immutable sequences of elements
- Sets: Unordered collections of unique elements
- Dictionaries: Unordered collections of key-value pairs
- NumPy arrays: Efficient arrays for numerical data, provided by the NumPy library
- Pandas DataFrames: 2D labeled data structures, provided by the pandas library
Example with NumPy Array:
If you're dealing with numerical data, numpy arrays are often more suitable, as they offer more functionality and are more efficient than Python lists or the array module:
import numpy as np
numpy_array = np.array([1, 2, 3, 4, 5])
Before using numpy, make sure to install it, as it is not included in the standard library. You can install it using pip:
pip install numpy