What are Python arrays?
Python arrays are mutable sequences of data. This means that the data in an array can be changed once it has been created. Arrays are created using square brackets ([]) and can contain any type of data, including integers, floats, strings, lists, and dictionaries.
How to create a Python array
To create a Python array, you simply enclose the elements of the array in square brackets. For example:
Python
my_array = [1, 2, 3, 4, 5]
This code creates an array containing the numbers 1 through 5.
How to access items in a Python array
To access items in a Python array, you use the square bracket operator ([]) and the index of the item. The index of the first item in an array is 0. For example:
Python
print(my_array[0]) # Outputs 1
print(my_array[2]) # Outputs 3
You can also use negative indices to access items from the end of the array. For example:
Python
print(my_array[-1]) # Outputs 5
print(my_array[-2]) # Outputs 4
How to iterate over a Python array
To iterate over a Python array, you can use the for loop. The for loop iterates over each item in the array and executes a block of code for each item. For example:
Python
for item in my_array:
print(item)
This code will print each item in the array to the console.
Python array methods
There are many Python array methods that can be used to perform various tasks on arrays, such as sorting, searching, and reversing. For more information on Python array methods, please refer to the official Python documentation.
Here are some examples of Python array methods:
Here are some additional tips for using Python arrays: