List methods:
- List is a pre-defined Object (class).
- List class is providing set of pre-defined methods(dynamic), we access using list object address.
- Using list functionality, we can process the list elements easily.
- The functionality is used to append, insert, remove, pop, sort, reverse and update the list as follows.
append(): Function that adds an element at the end of the List and returns the complete list with appended element.
l = [10,20,30]
print("List :", l)
l.append(40)
print("After append 40 :", l)
count(): Function that returns the specified element count in the List
l = [10, 20, 10, 40, 10]
print("List :", l)
print("Count of 10 :", l.count(10))
print("Count of 40 :", l.count(40))
print("Count of 50 :", l.count(50))
index():
- Function that returns index value of specified element.
- List supports duplicate elements.
- If the specified element is duplicated, it return first occurrence of index.
- Raises an exception if the specified element is not present in the list.
l = [10, 20, 10, 40, 20, 50]
print("List :", l)
print("index of 40 :", l.index(40))
print("index of 20 :", l.index(20))
print("index of 70 :", l.index(70))
Output:
List : [10, 20, 10, 40, 20, 50]
index of 40 : 3
index of 20 : 1
ValueError: 70 is not in list
Insert():
- Function that is used to insert element at specified index.
- After insertion, other elements in the list will shift to right.
- Element will be appended if the specified index is not present in that List.
l = [10,20,10,40]
print("List :", l)
print("insert 50 @ index : 2 :")
l.insert(2,50)
print("List :", l)
print("insert 70 @ index : -4 :")
l.insert(-4,70)
print("List :", l)
print("insert 90 @ index : 12 :") # append if out of bounds
l.insert(12,90)
print("List :", l)
Output:
List : [10, 20, 10, 40]
insert 50 @ index : 2 :
List : [10, 20, 50, 10, 40]
insert 70 @ index : -4 :
List : [10, 70, 20, 50, 10, 40]
insert 90 @ index : 12 :
List : [10, 70, 20, 50, 10, 40, 90]