A list is a collection of items stored in a single variable. Lists are ordered, mutable (changeable), and allow duplicate values.
# Empty list
empty_list = []
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "orange"]
# Mixed list
mixed = [1, "hello", 3.14, True]
Access items using their index (starting from 0):
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: orange (last item)
Use len() to get the number of items:
fruits = ["apple", "banana", "orange"]
print(len(fruits)) # Output: 3
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'orange']
fruits = ["apple", "orange"]
fruits.insert(1, "banana")
print(fruits) # Output: ['apple', 'banana', 'orange']
fruits = ["apple", "banana", "orange"]
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange']
fruits = ["apple", "banana", "orange"]
fruits.pop(1) # Removes "banana"
print(fruits) # Output: ['apple', 'orange']
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers) # Output: [1, 1, 3, 4, 5]
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Output: [5, 4, 3, 2, 1]
numbers = [1, 2, 2, 3, 2, 4]
print(numbers.count(2)) # Output: 3
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# orange
Get a portion of a list:
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [2, 3, 4]
print(numbers[:3]) # Output: [1, 2, 3]
print(numbers[2:]) # Output: [3, 4, 5]
Create a list of your favorite items, add and remove items, and practice sorting and looping!
Open Code Editor