Lists are mutable ordered containers. They’re similar to tuples, except they can be modified. They keep objects in the order you add them.
# Create a list
animals = ["dog", "cat", "horse", "rabbit"]
# Accessing items via index
print(animals[0])
print(animals[2])
print() # Blank line
# Iterating over a list
for animal in animals:
print(animal)
dog
horse
dog
cat
horse
rabbit
Adding Items to Lists
We can always add new items to a list. If you want to start with an empty list, you can simply use empty square brackets [] or you can use a built-in function: the list constructor function list().
# Create an empty list
numbers = list()
# Append some items to the end
numbers.append(8)
numbers.append(4)
numbers.append(9)
print(numbers)
# Insert the number 5 before the item
# at index 2.
numbers.insert(2, 5)
print(numbers)
[8, 4, 9]
[8, 4, 5, 9]
Modifying List Items
You can easily change an item in a list.
fruits = ["orange", "apple"]
print(fruits)
fruits[0] = "mango"
print(fruits)
['orange', 'apple']
['mango', 'apple']
Iterating Over Lists
You can iterate over a list in the same way that you iterate over tuples.
fruits = ["orange", "apple", "banana"]
for fruit in fruits:
print(fruit)
orange
apple
banana
You can obtain the number of items in any container with the len() builtin function. You can use this to iterate over a list with a range-based loop if you prefer.
fruits = ["orange", "apple", "banana"]
for i in range(len(fruits)):
print(fruits[i])
orange
apple
banana
Removing Items from Lists
You can remove an item from a list using the remove method. If you do this, the list has to check each item in turn until it finds the one you want to remove. A more efficient way to remove an item is to use its index and the del keyword.
fruits = ["orange", "apple", "mango", "banana", "orange"]
print(fruits)
# Remove first occurrence of 'orange'
fruits.remove("orange")
print(fruits)
# Remove item at index 1
del fruits[1]
print(fruits)
['orange', 'apple', 'mango', 'banana', 'orange']
['apple', 'mango', 'banana', 'orange']
['apple', 'banana', 'orange']
The Pop Method
Lists have a useful method called pop. By default this removes (and returns) the first item in the list, but if you supply an index to pop, you can remove and return other items.
fruits = ["orange", "apple", "mango", "banana", "orange"]
print(fruits)
unwanted = fruits.pop()
print(unwanted)
print(fruits)
unwanted = fruits.pop(1)
print(unwanted)
print(fruits)
['orange', 'apple', 'mango', 'banana', 'orange']
orange
['orange', 'apple', 'mango', 'banana']
apple
['orange', 'mango', 'banana']
Negative Indices
You can use negative indices to reference items in lists. -1 refers to the last item in the list.
numbers = [1, 2, 3, 4]
print(numbers)
print(numbers[-1])
print(numbers[-2])
[1, 2, 3, 4]
4
3
Check out the official Python docs on containers for more list methods.
Leave a Reply