Introduction
Python Data Types & Operators
Conditional Statements
Python Loops
Python Strings
Python Lists
Python Tuple
Here is a comprehensive list of Python List Methods that allow you to manipulate and interact with lists effectively:
1. append(x)
- Adds an element
x
to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
2. extend(iterable)
- Adds all elements from an iterable (e.g., another list, tuple, or string) to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
3. insert(i, x)
- Inserts an element
x
at the specified indexi
. All subsequent elements are shifted to the right.
Example:
my_list = [1, 2, 3]
my_list.insert(1, 'a') # Insert 'a' at index 1
print(my_list) # Output: [1, 'a', 2, 3]
4. remove(x)
- Removes the first occurrence of element
x
from the list. Raises aValueError
ifx
is not in the list.
Example:
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
5. pop([i])
- Removes and returns the element at index
i
. If no index is specified, it removes and returns the last element.
Example:
my_list = [1, 2, 3]
popped_item = my_list.pop(1) # Removes the item at index 1 (element '2')
print(my_list) # Output: [1, 3]
print(popped_item) # Output: 2
6. clear()
- Removes all elements from the list, leaving it empty.
Example:
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
7. index(x[, start[, end]])
- Returns the index of the first occurrence of element
x
in the list. The optionalstart
andend
parameters limit the search to the specified range. Raises aValueError
ifx
is not found.
Example:
my_list = [1, 2, 3, 2, 4]
index_of_2 = my_list.index(2)
print(index_of_2) # Output: 1
8. count(x)
- Returns the number of occurrences of element
x
in the list.
Example:
my_list = [1, 2, 3, 2, 4]
count_of_2 = my_list.count(2)
print(count_of_2) # Output: 2
9. sort(key=None, reverse=False)
- Sorts the list in ascending order (by default). You can specify the
key
parameter for a custom sorting order and thereverse
parameter to sort in descending order.
Example:
my_list = [3, 1, 4, 1, 5, 9, 2]
my_list.sort()
print(my_list) # Output: [1, 1, 2, 3, 4, 5, 9]
Sorting in reverse order:
my_list.sort(reverse=True)
print(my_list) # Output: [9, 5, 4, 3, 2, 1, 1]
10. reverse()
- Reverses the elements of the list in place.
Example:
my_list = [1, 2,4, 3]
my_list.reverse()
print(my_list) # Output: [3,4, 2, 1]