Python Core



Admission Enquiry Form


List methods in python

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

Example of append() method in list

The append() method adds an element to the end of the list.

     

li=[10,20,30,40,50]
li.append(60)
print(li)



Output

[10, 20, 30, 40, 50, 60]



Example of insert() method in list

insert() method inserts an element at a given index number

     

li=[10,20,30,40,50]
li.insert(2,25)
print(li)



Output

[10, 20, 25, 30, 40, 50]



Example of remove() method in list

remove() method is used to remove given element from the list

li=[10,20,30,40,50]
li.remove(30)
print(li)



Output

[10, 20, 40, 50]



Example of pop() method with specified position

pop() method is used to remove an element at a specified index number. If, no position is specified then it automatically removes the last element of the list.

li=[10,20,30,40,50]
li.pop(3)
print(li)


Output

[10, 20, 30, 50]



Example of pop() method without specified position

li=[10,20,30,40,50]
li.pop()
print(li)


Output

[10, 20, 30, 40]



Example of reverse() method in list

The reverse() method reverses the sorting order of the elements.


li=[10,20,30,40,50]
li.reverse()
print(li)


Output

[50, 40, 30, 20, 10]



Example of sort() method in list

sort() method is used to sort the elements in asceding order

li=[20,30,10,50,40]
li.sort()
print(li)


Output

[10, 20, 30, 40, 50]



Example of sort() method with string in list

li=['mouse','keyboard','cpu','monitor','speaker']
li.sort()
print(li)


Output

['cpu', 'keyboard', 'monitor', 'mouse', 'speaker']



Example of count() method in list

count() method returns the number of occurences of a particular element in list

li=[10,20,30,40,20,30,20,50]
l=li.count(20)
print(l)


Output

3



Example of counting total elements of list using len() function

li=[10,20,30,40,50]
l=len(li)
print(l)


Output

5



Example of copy() method in list

The copy() method returns a copy of the specified list.

li=[10,20,30,40,50]
cpy=li.copy()
print(cpy)


Output

[10, 20, 30, 40, 50]



Example of extend() method in list

The extend() method adds the specified list elements to the end of the current list.

li1=[10,20,30]
li2=[40,50]
li1.extend(li2)
print(li1)


Output

[10, 20, 30, 40, 50]



Example of clear() method in list

The clear() method removes all the elements from a list.

li=[10,20,30,40,50]
li.clear()
print(li)


Output

[]



Example of index() method in list

The index() method returns the position at the first occurrence of the specified value.

li=[10,20,30,40,50]
pos=li.index(30)
print(pos)


Output

2