A list is Python's ordered, changeable collection — the closest equivalent to PHP's indexed array, and by far the most commonly used collection type.
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # "apple"
print(fruits[2]) # "mango"
print(fruits[-1]) # "mango" — negative indexes count from the endfruits = ["apple", "banana"]
fruits.append("mango") # adds to the end
fruits[0] = "green apple" # overwrites index 0
fruits.remove("banana") # removes the first "banana" found
del fruits[0] # removes by index instead| Method | What it does |
|---|---|
| list.append(x) | Adds x to the end |
| list.insert(i, x) | Inserts x at a specific index |
| list.sort() | Sorts the list in place |
| list.reverse() | Reverses the list in place |
| len(list) | Number of items (a function, like with strings) |
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
# with the index too:
for index, fruit in enumerate(fruits):
print(index, fruit)for x in list is by far the most common way to loop in Python — you'll see it used constantly from here on. The Loops lesson later in this section covers Python's loops in full.
The same [start:end] slicing from the Strings lesson works on lists too — this is a general Python pattern, not something specific to strings:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:3]) # [20, 30]
print(numbers[:2]) # [10, 20]
print(numbers[-2:]) # [40, 50]