List Functions And Methods In Python Programing - Coderz*United

List Functions And Methods In Python Programing



List.pop(<index>)


  • Deletes an element from the given position in the list, and returns it.

  • If no index, pop() removes and returns the last item in the list.

  • Returns the item being deleted 

  • Raises an exception (runtime error) if the list is already empty 

L=[21,12,13,14,15

print(L.pop())

Out[1]: 15 

print(L.pop(2))

Out[1]: 13 

print(L)

Out[1]: [21, 12, 14] 

print(L.pop(5)

IndexError: pop index out of range 


List.index(<item>)  

  • Returns the index of first matched item from the list  

  • If the given item is not in the list, it raises an exception error. 

L=[11,12,13,14,15

print(L.index(13) ) 

Out[1]:

print(L.index(20) )

ValueError: 20 is not in list


List.insert(<pos>,<item>)

  • Append() and extend() insert the element(s) at the end of the list 

  • If you want to insert an element somewhere in between or any position of your choice, insert() method is used. 

  • <pos> is the index of the element before which the second argument is to be added 

  • Returns no value 

print(L)

Out[1]: [11, 12, 13, 14, 15] 

L.insert(5,19) 

print(L)

Out[1]: [11, 12, 13, 14, 15, 19] 

L.insert(9,19) 

print(L)

Out[1]: [11, 12, 13, 14, 15, 19, 19] 

L.insert(-9,19) 

print(L)

Out[1]: [19, 11, 12, 13, 14, 15, 19, 19] 

L.insert(3,19) 

Out[1]: [19, 11, 12, 19, 13, 14, 15, 19, 19]


List.remove(<value>) 

  • remove() function removes the first occurrence of given item from the list.

  • Does not return anything.  

  • pop() removes an element from the list based on index, but to remove an element based on value, remove() is used. 

print(L) 

Out[1]: [19, 11, 12, 19, 13, 14, 15, 19, 19] 

L.remove(11)

print(L)

Out[1]: [19, 12, 19, 13, 14, 15, 19, 19] 

L.remove(19)

print(L)

Out[1]: [12, 19, 13, 14, 15, 19, 19] 

L.remove(1)

ValueError: list.remove(x): x not in list


List.clear()  

  • Removes all items from the list .  

  • The list becomes empty after clear() is executed.  

  • Returns nothing. 


How is del L different from L.clear()?  

  • del L removes the elements as well as the list.  

  • L.clear() only removes the elements from the List. The List remains. The List object still exists as an empty list. 

L=[1,2,3,4

del L

print(L)

NameError: name 'L' is not defined 

L=[1,2,3,4

L.clear() 

print(L)

Out[1]: [ ] 


List.count(<item>)  

  • Returns the count of the item passed as an argument.  

  • If the element is not in the list, it returns 0. 

L=[11,12,13,19,14,19,16,19,19

print(L.count(19) )

Out[1]: 4 

print(L.count(9) )

Out[1]:


List.reverse()  

  • Reverses the item of the list in place.  

  • No new list is created.  

  • Returns no list. 

L=[11,12,13,14,15

L.reverse() 

print(L)

Out[1]: [15, 14, 13, 12, 11] 


L2=L.reverse() 

print(L2)

Out[1]: [15, 14, 13, 12, 11]