DEV Community

Ankit Dagar
Ankit Dagar

Posted on

List Methods of Python

1. append() :-

It add the element in the last of the list.
example:-

>>> alist=[]
>>> alist.append(1)
>>> alist.append(2)
>>> alist.append(3)
>>> alist
[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

2. clear() :-

It delete all the elements of the list.
example:

>>> alist.clear()
>>> alist
[]
Enter fullscreen mode Exit fullscreen mode

3. copy() :-

It returns a copy of a list.
example:-

>>> alist.append(1)
>>> alist.append(2)
>>> alist.append(3)
>>> blist=[]
>>> blist=alist.copy()
>>> blist
[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

4. count() :-

it counts the number of a elements present in a list
example:

>>> blist=[1, 2, 3, 1]
>>> blist.count(1)
2

Enter fullscreen mode Exit fullscreen mode

5. extend() :-

It add the elements of a list in the end of a new list.
example:

>>> alist.extend(blist)
>>> alist
[1, 2, 3, 1, 2, 3]

Enter fullscreen mode Exit fullscreen mode

6. index() :-

It returns the index of a first occurance of a specified value in a list.
example:

>>> alist.index(2)
1
Enter fullscreen mode Exit fullscreen mode

7. insert() :-

It insert a element at a specified index position.
example:

>>> alist.insert(-1,4)
>>> alist
[1, 2, 3, 1, 2, 4, 3]
Enter fullscreen mode Exit fullscreen mode

8. pop() :-

It removes the last element or the element on the given index.
example:

>>> alist.pop(-2)
4
>>> alist
[1, 2, 3, 1, 2, 3]
>>> alist.pop()
3
>>> alist
[1, 2, 3, 1, 2]
Enter fullscreen mode Exit fullscreen mode

9. remove() :

It removes the first occurance of the specified element in a list.
example:

>>> alist.remove(3)
>>> alist
[1, 2, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

10. reverse() :-

It reverses the order of the list.
example:

>>> alist.reverse()
>>> alist
[2, 1, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

11. sort() :-

It sorts the order of a list.
example:

>>>alist.sort()
>>>alist
[1, 1, 2, 2, 3]
Enter fullscreen mode Exit fullscreen mode

References

GeeksforGeeks
W3Schools
freecodecamp

Top comments (0)