List Methods
Python lists have several built-in methods that allow you to perform various operations on lists. Here are some commonly used list methods:
append(x)
: Adds an elementx
to the end of the list.numbers = [1, 2, 3] numbers.append(4) # Now, numbers is [1, 2, 3, 4]
extend(iterable)
: Extends the list by appending elements from the iterable.numbers = [1, 2, 3] numbers.extend([4, 5, 6]) # Now, numbers is [1, 2, 3, 4, 5, 6]
insert(i, x)
: Inserts elementx
at the specified indexi
.numbers = [1, 2, 3] numbers.insert(1, 10) # Now, numbers is [1, 10, 2, 3]
remove(x)
: Removes the first occurrence of elementx
from the list.numbers = [1, 2, 3, 4, 3, 5] numbers.remove(3) # Now, numbers is [1, 2, 4, 3, 5]
pop([i])
: Removes and returns the element at indexi
. Ifi
is not provided, it removes and returns the last element.numbers = [1, 2, 3, 4, 5] popped_value = numbers.pop(2) # Now, numbers is [1, 2, 4, 5], and popped_value is 3
clear()
: Removes all elements from the list, leaving it empty.numbers = [1, 2, 3, 4, 5] numbers.clear() # Now, numbers is []
index(x[, start[, end]])
: Returns the index of the first occurrence of elementx
in the list. Optionally, the search can be limited to the specified range[start:end]
.numbers = [1, 2, 3, 4, 5] index_of_3 = numbers.index(3) # index_of_3 is 2
count(x)
: Returns the number of occurrences of elementx
in the list.numbers = [1, 2, 3, 4, 3, 5] count_of_3 = numbers.count(3) # count_of_3 is 2
sort(key=None, reverse=False)
: Sorts the elements of the list in ascending order. Thekey
andreverse
parameters allow customization.numbers = [4, 2, 1, 3, 5] numbers.sort() # Now, numbers is [1, 2, 3, 4, 5]
reverse()
: Reverses the elements of the list in-place.numbers = [1, 2, 3, 4, 5] numbers.reverse() # Now, numbers is [5, 4, 3, 2, 1]
These are just a few examples of the many list methods available in Python. Understanding and using these methods can greatly simplify list manipulation tasks in your programs.