A list is a mutable, ordered collection of items in Python. Each item inside a list is referred to as an element. Since lists are mutable, their contents can be modified after creation.
You can create lists using square brackets []
and separating items with commas.
fruits = ["apple", "banana", "cherry"]
Elements can be accessed by their index.
print(fruits[0]) # Outputs: apple
print(len(fruits)) # Outputs: 3
vegetables = ["carrot", "broccoli"]
food = fruits + vegetables
print(food) # Outputs: ['apple', 'banana', 'cherry', 'carrot', 'broccoli']
print(fruits * 2) # Outputs: ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry']
print("apple" in fruits) # Outputs: True
fruits.append("grape")
print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'grape']
fruits.extend(["mango", "pineapple"])
print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'grape', 'mango', 'pineapple']
fruits.insert(1, "orange") # Insert "orange" at the second position
print(fruits) # Outputs: ['apple', 'orange', 'banana', 'cherry', 'grape', 'mango', 'pineapple']
fruits.remove("banana")
print(fruits) # Outputs: ['apple', 'orange', 'cherry', 'grape', 'mango', 'pineapple']
removed_fruit = fruits.pop(0)
print(removed_fruit) # Outputs: apple
print(fruits) # Outputs: ['orange', 'cherry', 'grape', 'mango', 'pineapple']
position = fruits.index("cherry")
print(position) # Outputs: 1
num_cherries = fruits.count("cherry")
print(num_cherries) # Outputs: 1
fruits.sort()
print(fruits) # Outputs: ['cherry', 'grape', 'mango', 'orange', 'pineapple']
fruits.reverse()
print(fruits) # Outputs: ['pineapple', 'orange', 'mango', 'grape', 'cherry']
fruits.clear()
print(fruits) # Outputs: []
Lists are one of Python’s most versatile and commonly used data structures. Understanding the operations and methods associated with lists provides a robust foundation for tackling more complex problems and data manipulations in Python.