List Methods (e.g., sort, reverse, count, extend) in Python Code
In Python, lists are a versatile and widely-used data structure. Here are some common methods available for lists:
append(x)
Adds an item x to the end of the list.
Python Code
lst = [1, 2, 3]
lst.append(4)
# lst is now [1, 2, 3, 4]
extend(iterable)
Extends the list by appending all the items from the iterable.
Python Code
lst = [1, 2, 3]
lst.extend([4, 5])
# lst is now [1, 2, 3, 4, 5]
insert(i, x)
Inserts an item x at a given position i.
Python Code
lst = [1, 2, 3]
lst.insert(1, 'a')
# lst is now [1, 'a', 2, 3]
remove(x)
Removes the first occurrence of an item x from the list.
Python Code
lst = [1, 2, 3, 2]
lst.remove(2)
# lst is now [1, 3, 2]
pop([i])
Removes and returns the item at position i. If i is not specified, removes and returns the last item.
Python Code
lst = [1, 2, 3]
item = lst.pop()
# item is 3, lst is now [1, 2]
clear()
Removes all items from the list.
Python Code
lst = [1, 2, 3]
lst.clear()
# lst is now []
index(x[, start[, end]])
Returns the index of the first occurrence of an item x (searching within optional start and end bounds).
Python Code
lst = [1, 2, 3, 2]
idx = lst.index(2)
# idx is 1
count(x)
Returns the number of times an item x appears in the list.
Python Code
lst = [1, 2, 2, 3]
count = lst.count(2)
# count is 2
sort(key=None, reverse=False)
Sorts the items of the list in place (the arguments can be used for sort customization).
Python Code
lst = [3, 1, 2]
lst.sort()
# lst is now [1, 2, 3]
reverse()
Reverses the elements of the list in place.
Python Code
lst = [1, 2, 3]
lst.reverse()
# lst is now [3, 2, 1]
copy()
Returns a shallow copy of the list.
Python Code
lst = [1, 2, 3]
lst_copy = lst.copy()
# lst_copy is [1, 2, 3]
__len__()
Returns the length of the list.
Python Code
lst = [1, 2, 3]
length = len(lst)
# length is 3
__getitem__(i)
Returns the item at position i.
Python Code
lst = [1, 2, 3]
item = lst[1]
# item is 2
__setitem__(i, x)
Sets the item at position i to x.
Python Code
lst = [1, 2, 3]
lst[1] = 'a'
# lst is now [1, 'a', 3]
__delitem__(i)
Deletes the item at position i.
Python Code
lst = [1, 2, 3]
del lst[1]
# lst is now [1, 3]
These methods provide a wide range of functionalities for manipulating and accessing list elements.
Top of Form