List Functions

List Functions

Python has a lot of list methods that allow us to work with lists. In this tutorial, you will find all the list methods to work with Python lists.

1. len()

Returns the number of elements present in the list.

E.g

n = [10, 20, 30, 40] 
print(len(n) ==> 4
2. count()

It returns the number of occurrences of specified item in the list.

n=[1,2,2,2,2,3,3] 
print(n.count(1)) // 1
print(n.count(2)) // 4
print(n.count(3)) // 2
print(n.count(4)) // 0
3. index()

Returns the index of first occurrence of the specified item.

n = [1, 2, 2, 2, 2, 3, 3] 
print(n.index(1)) // 0 
print(n.index(2)) // 1 
print(n.index(3)) // 5 
print(n.index(4)) // ValueError: 4 is not in list

Note

If the specified element not present in the list then we will get ValueError. Hence before index() method we have to check whether item present in the list or not by using in operator.

print( 4 in n) // False
4. append()

We can use append() function to add item at the end of the list.

list=[] 
list.append("A") 
list.append("B") 
list.append("C") 
print(list)

Output

> py test.py
['A', 'B', 'C']

E.g: To add all elements to list up to 100 which are divisible by 10.

list=[] 
for i in range(101): 
    if i%10==0: 
        list.append(i) 
print(list)

Output

> py test.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
5. insert()

To insert item at specified index position

n=[1,2,3,4,5] 
n.insert(1,888) 
print(n)

Output

> py test.py
[1, 888, 2, 3, 4, 5]

E.g 2

n=[1,2,3,4,5] 
n.insert(10,777) 
n.insert(-10,999) 
print(n)

Output

> py test.py
[999, 1, 2, 3, 4, 5, 777]

Note

If the specified index is greater than max index then element will be inserted at last position. If the specified index is smaller than min index then element will be inserted at first position.

List Functions


Scroll to top