List Methods in Python
List Methods in Python
.
1 append(): Used for appending and adding elements to List.It is used to add elements to
the last position of List.
Syntax:
list.append (element)
# Adds List Element as value of List.
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)
Output:
['Mathematics', 'chemistry', 1997, 2000, 20544]
Output:
['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]
List1.extend(List2)
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1)
# Add List1 to List2 now
List2.extend(List1)
print(List2)
Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
Syntax:
sum(List)
List = [1, 2, 3, 4, 5]
print(sum(List))
Output:
15
Output:
Traceback (most recent call last):
File "", line 1, in
sum(List)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Syntax:
List.count(element)
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output:
4
length:Calculates total length of List.
Syntax:
len(list_name)
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
Output:
10
index(): Returns the index of first occurrence. Start and End index are not
necessary parameters.
Syntax:
List.index(element[,start[,end]])
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))
Output:
1
min() : Calculates minimum of all the elements of List.
Syntax:
min(List)
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(min(List))
Output:
1.054
max(): Calculates maximum of all the elements of List.
Syntax:
max(List)
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(max(List))
Output:
5.33
Output:
[1.054, 2.3, 2.5, 3, 4.445, 5.33]
pop(): Index is not a necessary parameter, if not mentioned takes the last index.
Syntax:
list.pop([index])
Note: Index must be in range of the List, elsewise IndexErrors occurs
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop())
Output:
2.5
del() : Element to be deleted is mentioned using list name and index.
Syntax:
del list.[index]
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
del List[0]
print(List)
Output:
[4.445, 3, 5.33, 1.054, 2.5]
remove(): Element to be deleted is mentioned using list name and element.
Syntax:
list.remove(element)
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
List.remove(3)
print(List)
Output:
[2.3, 4.445, 5.33, 1.054, 2.5]