Python - Arrays
In Python, you can access elements in a list (or array) using indexing. The index represents the position of an element in the list, and it starts from 0 for the first element. Negative indexing is also allowed, with -1 representing the last element, -2 representing the second-to-last element, and so on.
Here is an example program demonstrating how to access elements in a list using indexing:
# Create a list
my_list = [10, 20, 30, 40, 50]
# Access elements using positive indexing
first_element = my_list[0]
second_element = my_list[1]
# Access elements using negative indexing
last_element = my_list[-1]
second_to_last_element = my_list[-2]
# Display the accessed elements
print("First Element:", first_element)
print("Second Element:", second_element)
print("Last Element:", last_element)
print("Second-to-Last Element:", second_to_last_element)
Output:
First Element: 10 Second Element: 20 Last Element: 50 Second-to-Last Element: 40
In this example, the list my_list
is created, and elements are accessed using both positive and negative indexing.
In Python, a multidimensional array is essentially a list of lists, where each element in the outer list is a list representing a row or sub-array. This structure allows you to create arrays with multiple dimensions (rows and columns).
Here is an example program demonstrating the concept of multidimensional arrays:
# Create a 2D array (3x3)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Access elements in the 2D array
element_1_2 = matrix[1][2]
# Display the accessed element
print("Element at row 1, column 2:", element_1_2)
Output:
Element at row 1, column 2: 6
In this example, matrix
is a 2D array, and we access an element at row 1, column 2 using indexing.
You can check the length of an array in Python using the len()
function. Here is an example program demonstrating how to check the length of an array:
# Create an array
my_array = [1, 2, 3, 4, 5]
# Check the length of the array
array_length = len(my_array)
# Display the length
print("Length of the array:", array_length)
Output:
Length of the array: 5
In this example, the len()
function is used to determine the number of elements in the array my_array
.
Slicing is a technique in Python that allows you to extract a portion of an array. It is done using the colon (:
) operator. Here's an example program demonstrating the use of slicing with arrays:
# Create an array
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Slice the array to get elements from index 2 to 5 (excluding 5)
sliced_array = my_array[2:5]
# Display the sliced array
print("Sliced Array:", sliced_array)
Output:
Sliced Array: [3, 4, 5]
In this example, the array my_array
is sliced using the syntax my_array[start:stop]
. The resulting sliced_array
includes elements from index 2 to 4 (excluding 5).