Lists
List manipulation methods and functions
len(list)
It returns the length of the list, i.e. the number of elements in the list.
l=[1,2,3,4]
print(len(l))
Output
4
list.index(item)
It returns the index of the first matched item from the list.
l=[1,2,3,4]
print(l.index(3))
Output
2
list.append(item)
It adds an item at the end of a list
l=[1,2,3,4]
l.append(5)
print(l)
OR
l=[1,2,3,4]
a=5
l.append(a)
print(l)
Output
[1,2,3,4,5]
list.extend(item)
It adds multiple items at the end of a list.
l=[1,2,3,4]
l.extend([5,6,7,8])
print(l)
OR
l=[1,2,3,4]
a=[5,6,7,8]
l.extend(a)
print(l)
Output
[1, 2, 3, 4, 5, 6, 7, 8]
list.insert(position, item)
This function is used to insert a particular item/element at a given index
l=[1,2,3,4]
l.insert(3,5)
print(l)
Output
[1, 2, 3, 5, 4]
list.pop(index)
This pop() is used to remove a certain item at the specified index from the list
l=[1,2,3,4]
l.pop(2)
print(l)
Output
[1, 2, 4]
list.remove(value)
The remove() method is used to remove an element from the list by specifying the element
l=[1,2,3,4]
l.remove(2)
print(l)
Output
[1, 3, 4]
list.clear()
This method removes all the items from the list and the list becomes an empty list. This function does not return anything
l=[1,2,3,4]
l.clear()
print(l)
Output
[]
list.count(item)
This method returns the number of occurrences of the specified element in the list
l=[1,2,3,4,3]
print(l.count(3))
Output
2
list.reverse()
This function reverses the order of items in the list
l=[1,2,3,4]
l.reverse()
print(l)
Output
[4,3,2,1]
list.sort()
It sorts the items into ascending order by default. To arrange them in decreasing order, the funtion will be list.sort(reverse=True)
l=[1,3,4,2]
l.sort()
print(l)
Output
[1, 2, 3, 4]
max(list)
It returns the item with maximum value
l=[1,2,3,4]
print(max(l))
Output
4
min(list)
It returns the item with minimum value
l=[1,2,3,4]
print(min(l))
Output
1
sum(list)
It returns the sum of the elements in the list
l=[1,2,3,4]
print(sum(l))
Output
10
Comments
Post a Comment