List Methods in Python

Python lists come with a variety of built-in methods that allow you to perform common operations such as adding, removing, or searching for elements. Understanding these methods is crucial for efficient list manipulation.

Common List Methods:

Examples:

Python
fruits = ["apple", "banana", "cherry"]

# Append an item
fruits.append("date")
print(fruits)  # Output: ["apple", "banana", "cherry", "date"]

# Insert an item at index 1
fruits.insert(1, "blueberry")
print(fruits)  # Output: ["apple", "blueberry", "banana", "cherry", "date"]

# Remove an item
fruits.remove("banana")
print(fruits)  # Output: ["apple", "blueberry", "cherry", "date"]

# Sort the list in ascending order
fruits.sort()
print(fruits)  # Output: ["apple", "blueberry", "cherry", "date"]

# Reverse the order of the list
fruits.reverse()
print(fruits)  # Output: ["date", "cherry", "blueberry", "apple"]

# Get the index of an item
index = fruits.index("cherry")
print(index)  # Output: 1

# Count occurrences of an item
count = fruits.count("apple")
print(count)  # Output: 1

# Copy the list
copied_fruits = fruits.copy()
print(copied_fruits)  # Output: ["date", "cherry", "blueberry", "apple"]

# Clear the list
fruits.clear()
print(fruits)  # Output: []

These methods are fundamental to working with lists and provide powerful tools for list manipulation, allowing you to easily manage and transform list data.