Loading lessons...
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.
python
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
python
print(cars[0])
### Ford
Change a value
python
cars[0] = "Toyota"
print(cars)
### ['Toyota', 'Volvo', 'BMW']
Length
python
print(len(cars))
### 3
Loop through
python
for x in cars:
print(x)
Add an item
python
cars.append("Honda")
Remove an item
python
cars.pop(1)
Or remove by value:
python
cars.remove("Volvo")
The real "array" module
If you truly need a C-style typed array, Python has an array module:
python
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.