DEV Community

NK1FC
NK1FC

Posted on • Updated on

Python List Methods

1- append(element)

Add the element at the end of the list.

 a=[1,2,3,4,5]
 a.append(6) # add the element to the end of the list
 print(a)
 # output-[1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

2- clear()

Remove all the elements of the list.

a=[1,2,3,4,5]
a.clear() #remove all the element
print(a)
# output-[]
Enter fullscreen mode Exit fullscreen mode

3- copy()

Create a copy of the list.

a=[1,2,3,4,5]
b=a.copy() #copy of list
print(b)
# output-[1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

4- count(value)

Gives the count of the number of elements of the specified value.

a=[1,2,3,2,5,2]
b=a.count(2) #Count the number of elements of the specified value in the list.
print(b)
# output-3
Enter fullscreen mode Exit fullscreen mode

5- extend(iterable)

Add all the elements of iterable(string, tuple, list, set) to the list

a=[1,2]
a.extend('abc') # char of string will be added a=[1, 2, 'a', 'b', 'c'].
a.extend([1,2]) # element of the list will be added a=[1, 2, 'a', 'b', 'c', 1, 2]
print(a)
# output-[1, 2, 'a', 'b', 'c', 1, 2]
Enter fullscreen mode Exit fullscreen mode

6- index(element)

Return the index of the first occurrence of the element.

a=[1,2,3,2,5,2]
b=a.index(2) #the index of the first occurrence of 2.
print(b)
# output-1
Enter fullscreen mode Exit fullscreen mode

7- insert(position, element)

Add the element at the specified position.

a=[1,2,3,2,5,2]
a.insert(2,'a') #Count the number of elements of the specified value in the list.
print(a)
# output-[1, 2, 'a', 3, 2, 5, 2]
Enter fullscreen mode Exit fullscreen mode

8- pop(postion)

Remove the element at the specified position if the position is not mentioned then the last element will be removed

a=[1,2,3]
a.pop() #Remove the last element of the list.
a.pop(0) #Remove the element at 0 position
print(a)
# output-[2]
Enter fullscreen mode Exit fullscreen mode

9- remove(element)

Remove the specified element at the first occurrence and throw an error if the element is not in the list.

a=[1,2,3,2,4,5]
a.remove(2) # remove the first occurrence of  2 from the list.
print(a)
# output-[1,3,2,4,5]
Enter fullscreen mode Exit fullscreen mode

10- reverse()

Reverse the list

a=[1,2,3]
a.reverse()# Reverse the list.
print(a)
# output-[3,2,1]
Enter fullscreen mode Exit fullscreen mode

11- sort()

Sort the list.

a=[3,1,2]
a.sort()# Sort the list.
print(a)
# output- [1,2,3]
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)