Python List Methods with Examples

Python List type is used to store single or more items in a single variable. The list is a very popular data type and used for different cases. Python list provides very similar functionality to the array in order programming languages. Python provides different methods in order to work with list types. In this tutorial, we examine the list methods.

append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list items
sort()Sorts the list items decremental

List append() Method

The list append() method is used to add or append a new item to the end of the list.

fruits = ['apple', 'banana', 'melon']

fruits.append('orange')

List clear() Method

The list clear() method is used to clear or remove all items in a list.

fruits = ['apple', 'banana', 'melon']

fruits.clear()

List copy() Method

The list copy() method is used to copy all items into a new list.

fruits = ['apple', 'banana', 'melon']

new_fruits = fruits.copy()

List count() Method

The list count() method is used to return the count of items.

fruits = ['apple', 'banana', 'melon']

list_count = fruits.count()

List extend() Method

The list extend() method is used to add another list or multiple items to the existing list.

fruits = ['apple', 'banana', 'melon']

fruits.extend(['cherry','carrot'])

List index() Method

The list index() method is used to return index number for the specified item.

fruits = ['apple', 'banana', 'melon']

index = fruits.index('banana')

List insert() Method

The list insert() method is used to insert new items to the specified position.

fruits = ['apple', 'melon']

index = fruits.index( 1 , 'banana')

List pop() Method

The list pop() method is used to remove the item with the specified index.

fruits = ['apple', 'banana', 'melon']

index = fruits.pop(1)

List remove() Method

The list remove() method is used to remove the specified item.

fruits = ['apple', 'banana', 'melon']

index = fruits.remove('banana')

List reverse() Method

The list reverse() method reverses the sorting order of the item.

fruits = ['apple', 'banana', 'melon']

index = fruits.reverse()

List sort() Method

The list sort() method is used to sort items in the list.

fruits = ['apple' , 'melon' , 'banana']

index = fruits.sort()

Leave a Comment