python-arrays.md

#Python Arrays

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

#Arrays

To work with "true" arrays in Python, you typically import a library like NumPy. However, this page demonstrates how to use Lists to achieve the same goals.

Arrays are used to store multiple values in one single variable.

#Example

Create an array containing car names:

pythoncars = ["Ford", "Volvo", "BMW"]

#What is an Array?

An array is a special variable which can hold more than one value at a time. If you have a list of items, storing them in single variables would look like this:

pythoncar1 = "Ford"
car2 = "Volvo"
car3 = "BMW"

Why use an array?


#Accessing Elements

You refer to an array element by its index number.

#Examples

Get the value of the first array item:

pythonx = cars[0]

Modify the value of the first array item:

pythoncars[0] = "Toyota"

#The Length of an Array

Use the len() method to return the number of elements in an array.

#Example

pythonx = len(cars)
Note: The length of an array is always one more than the highest array index.

#Looping Array Elements

You can use the for in loop to iterate through all the elements.

#Example

Print each item in the cars array:

pythonfor x in cars:
  print(x)

#Adding Array Elements

Use the append() method to add an element to the end of the array.

#Example

pythoncars.append("Honda")

#Removing Array Elements

There are two primary ways to remove items:

  1. pop(): Removes an element at a specific position.
python    # Delete the second element
    cars.pop(1)
  1. remove(): Removes an element by value.
python    # Delete the element with the value "Volvo"
    cars.remove("Volvo")
Note: The remove() method only removes the first occurrence of the specified value.

#Array Methods

Python has a set of built-in methods that you can use on lists/arrays:

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable) to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

Reminder: Python does not have built-in support for Arrays; Python Lists are the standard alternative.