11.10 List Methods

By | October 2, 2021

List Methods

Example:

Add an element to the fruits list:
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits.append(“orange”)

Output:
[‘apple’, ‘banana’, ‘cherry’, ‘orange’]

Python has a set of built-in methods that you can use on lists.

MethodSyntaxDescription
append()list.append(elmnt)Adds an element at the end of the list
clear()list.clear()Removes all the elements from the list
copy()list.copy()Returns a copy of the list
count()list.count(value)Returns the number of elements with the specified value
extend()list.extend(iterable)Add the elements of a list (or any iterable), to the end of the current list
index()list.index(elmnt)Returns the index of the first element with the specified value
insert()list.insert(poselmnt)Adds an element at the specified position
pop()list.pop(pos)Removes the element at the specified position
remove()list.remove(elmnt)Removes the item with the specified value
reverse()list.reverse()Reverses the order of the list
sort()list.sort(reverse=True|False, key=myFunc)Sorts the list

Leave a Reply

Your email address will not be published. Required fields are marked *