What is an Array?
An array is a collection of elements stored in contiguous memory locations. Each element can be accessed using its index.Example:
num1 = 10
num2 = 20
num3 = 30
You can store them in a single array (list):
numbers = [10, 20, 30]
This makes your code cleaner & easier to manage.
Creating Arrays in Python
The Python does not have a built-in array data type like some other programming languages. Instead, Python lists are commonly used as arrays.Example:
fruits = ["Apple", "Mango", "Orange"]
print(fruits)
Output:
['Apple', 'Mango', 'Orange']
Accessing Array Elements
The Array elements are accessed using their index. Indexing starts from 0.Example:
colors = ["Red", "Green", "Blue"]
print(colors[0])
print(colors[2])
Output:
Red
Blue
Adding Elements to an Array
Using append()
Adds an element to the end of the array.numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
Output:
[1, 2, 3, 4]
Using insert()
Adds an element at a specific position.numbers = [1, 2, 4]
numbers.insert(2, 3)
print(numbers)
Output:
[1, 2, 3, 4]
Finding the Length of an Array
Use the len() function to count the number of elements.Example:
languages = ["Python", "Java", "C++", "JavaScript"]
print(len(languages))
Output:
4
Array Slicing
The Slicing allows you to access a range of elements.Example:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
Output:
[20, 30, 40]
Sorting an Array
Ascending Order
numbers = [5, 2, 8, 1, 3]
numbers.sort()
print(numbers)
Output:
numbers.sort()
print(numbers)
Output:
[1, 2, 3, 5, 8]
Descending Order
numbers = [5, 2, 8, 1, 3]
numbers.sort(reverse=True)
print(numbers)
Output:
numbers.sort(reverse=True)
print(numbers)
Output:
[8, 5, 3, 2, 1]
Multi-Dimensional Arrays
The Python supports nested lists which can be used as multi-dimensional arrays.Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2])
Output:
6
Advantages of Arrays
- Easy to store multiple values.
- Fast access using indexes.
- Simplifies data management.
- Supports sorting & searching operations.
- Useful for handling large datasets.
When to Use Arrays in Python
Use arrays when you need to:- Store collections of data.
- Process multiple values efficiently.
- Perform sorting & searching operations.
- Work with numerical datasets.