Note: Arrays have no built-in support in Python, but you can use Python Lists in their place.
Arrays
Note: Everything on this page uses LISTS as ARRAYS. Working with real arrays in Python requires importing a library, such as NumPy.
An array keeps several values together in one variable:
Example
Store three car names in an array:
Output: complete Python program
cars = ["Ford", "Volvo", "BMW"]
What is an Array?
An array is a special kind of variable that can hold more than one value at once.
Suppose you have a list of items, such as car names. Keeping each car in its own variable might look like this:
That falls apart quickly, though. How would you loop through the cars to find a particular one? And what about 300 cars instead of 3?
An array solves both problems!
It keeps many values under one name, and you can get to any of them with an index number.
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
Access the Elements of an Array
To reach an element of an array, use its index number.
Example
Read the first item of the array:
Output: complete Python program
cars = ["Ford", "Volvo", "BMW"]
x = cars[0]
print(x)
Example
Give the first item of the array a new value:
Output: complete Python program
cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)
The Length of an Array
The len() function returns the length of an array, meaning how many elements it has.
Note: This length is always one more than the highest index in the array.
Example
Count how many elements cars holds:
Output: complete Python program
cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)
Looping Array Elements
A for in loop visits every element of an array in turn.
Example
Print every item in cars:
Output: complete Python program
cars = ["Ford", "Volvo", "BMW"]
for x in cars:
print(x)
Adding Array Elements
To add an element to an array, call the append() method.
Example
Add one more car to the end of cars:
Output: complete Python program
cars = ["Ford", "Volvo", "BMW"]
cars.append("Honda")
print(cars)
Removing Array Elements
To take an element out of an array, call the pop() method.
You can also call the remove() method, which takes out an element by its value.
Note: If a value appears more than once, remove() only deletes its earliest match.
Example
Delete the second element of cars:
Output: complete Python program
cars = ["Ford", "Volvo", "BMW"]
cars.pop(1)
print(cars)
Example
Delete the element whose value is "Volvo":
Output: complete Python program
cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)