Python Logo

Arrays


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:

  • sort() - Sorts the array in ascending order.
  • reverse() - Reverses the order of the array.
  • count() - Returns the number of times a specific item appears in the array.
  • index() - Returns the index of the first occurrence of a specific item in the array.
  • append() - Adds an item to the end of the array.
  • insert() - Inserts an item at a specific index in the array.
  • remove() - Removes an item from the array.

Here are some additional tips for using Python arrays:

  • Use descriptive variable names for your arrays. This will make your code more readable and easier to maintain.
  • Add comments to your code to explain what your arrays are used for. This will help other developers understand your code and make it easier to debug.
  • Be careful when using the append() and insert() methods, as they can lead to infinite loops if used incorrectly.
  • Use the isinstance() function to check the data type of a variable before using it as an array. This can help you to avoid errors.