Python List (Part III)*Mpy2iVRxQT-R_GMN

Original Source Here

smart and simple

Photo by Sigmund on Unsplash

In this article, we will discuss functions in the list

If we want to add an element to a list, add one list in another list, find the occurrences of elements in a list, and so on

There are already a lot of functions that are already defined. we just have to know how to use those.

List of functions:

  • count
  • sort
  • append
  • insert
  • extend
  • pop
  • remove
  • clear
  • reverse
  • index
  • copy

If you are using a jupyter notebook then just type list_name.TAB button you will see all the functions related to the list.

After writing a function to know more about a particular function type: SHIFT + TAB

let’s see one by one

list1 = [10, 20, 30, 40,50,10]

If I want the sum of all elements in a given list:


For calculating occurrences of a particular element

#output: 2

we can directly sort a list in just one line of function but remember the time complexity will be n log n because internally it is a quick sort.


Insert items in a list

Three functions are there to insert elements in a list

  • .append(value)
  • .insert(index,value)
  • .extend(list of elements)

suppose I have a list: my_list = [1, 2, 3]

Always remember append will always insert element at the endmy_list.append(4)

now the elements in list are: [1,2,3,4]


now the elements in list are:[1,2,10,3,4]


Remove item from list

  • .pop(index)
  • .clear()
  • .remove(item to remove)

pop will remove item according to the index, by default index will be -1. pop always returns deleted item.

clear will delete all the items from list

remove will delete value given to function, if there are two values which are same remove will delete the first one

my_list2 = [10,20,30,40,50,60]


now the elements in list are: [10,20,30,40,50]


now the elements in list are: [10,30,40,50]


now the elements in list are: [10,30,40,50]


index function will simply return index of given item

#output: 2

reverse will reverse the list


It was pretty easy I guess, try it yourself then your concepts will get more clear.

In the next article, we will discuss shallow copy and deep copy which are the most important and frequently asked questions in an interview.


Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: