Python List Methods
Master essential list methods for data manipulation
📋 Working with Lists
Lists are ordered collections that can store multiple items. Python provides many built-in methods to work with lists efficiently.
# Basic list operations
fruits = ["apple", "banana"]
fruits.append("orange") # Add item
print(fruits) # ['apple', 'banana', 'orange']
List Method Categories
Adding Items
Add new elements to your list
Removing Items
Delete elements from your list
Finding Items
Search and locate elements
Organizing Items
Sort and arrange your list
🔹 Adding Items to Lists
append() - Add One Item
Adds a single item to the end of the list
colors = ["red", "blue"]
colors.append("green")
print(colors) # ['red', 'blue', 'green']
insert() - Add at Specific Position
Adds an item at a specific index
numbers = [1, 3, 4]
numbers.insert(1, 2) # Insert 2 at index 1
print(numbers) # [1, 2, 3, 4]
extend() - Add Multiple Items
Adds all items from another list
pets = ["cat", "dog"]
more_pets = ["fish", "bird"]
pets.extend(more_pets)
print(pets) # ['cat', 'dog', 'fish', 'bird']
🔹 Removing Items from Lists
remove() - Remove by Value
Removes the first occurrence of a value
fruits = ["apple", "banana", "apple"]
fruits.remove("apple") # Removes first "apple"
print(fruits) # ['banana', 'apple']
pop() - Remove by Index
Removes and returns item at index (last item if no index)
items = ["a", "b", "c"]
last = items.pop() # Remove last item
print(last) # 'c'
print(items) # ['a', 'b']
first = items.pop(0) # Remove first item
print(first) # 'a'
print(items) # ['b']
clear() - Remove All Items
Removes all items from the list
numbers = [1, 2, 3, 4, 5]
numbers.clear()
print(numbers) # []
🔹 Finding Items in Lists
index() - Find Position
Returns the index of the first occurrence
colors = ["red", "blue", "green"]
position = colors.index("blue")
print(position) # 1
count() - Count Occurrences
Returns how many times a value appears
numbers = [1, 2, 2, 3, 2]
count = numbers.count(2)
print(count) # 3
🔹 Organizing Lists
sort() - Sort in Place
Sorts the list permanently
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # [1, 2, 3, 4]
# Sort in reverse
numbers.sort(reverse=True)
print(numbers) # [4, 3, 2, 1]
reverse() - Reverse Order
Reverses the order of items
letters = ["a", "b", "c"]
letters.reverse()
print(letters) # ['c', 'b', 'a']
copy() - Make a Copy
Creates a shallow copy of the list
original = [1, 2, 3]
backup = original.copy()
original.append(4)
print(original) # [1, 2, 3, 4]
print(backup) # [1, 2, 3]