Loading lessons...
Arrays
Arrays
Python has no built-in array type with the C meaning. The closest everyday tool is the list, which acts like a flexible array.
cars = ["Ford", "Volvo", "BMW"]
print(cars)
Lists are the go-to
For normal Python programs, use lists. They do everything an array does plus more.
Access by index
print(cars[0]) # Ford
Change a value
cars[0] = "Toyota"
print(cars) # ['Toyota', 'Volvo', 'BMW']
Length
print(len(cars)) # 3
Loop through
for x in cars:
print(x)
Add an item
cars.append("Honda")
Remove an item
cars.pop(1)
Or remove by value:
cars.remove("Volvo")
The real "array" module
If you truly need a C-style typed array, Python has an array module:
import array as arr
nums = arr.array("d", [1.1, 2.2, 3.3])
It stores numbers compactly, but for daily work lists win.
TL;DR
- Use lists as Python's arrays.
- Index, change, loop, append, and pop work naturally.
- The array module exists for compact typed data.
- Most of the time, a list is all you need.