Python List (Part III)
smart and simple
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:
sum(list1)
#output:160
For calculating occurrences of a particular element
list1.count(10)
#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.
list1.sort()
print(list1)
#output:[10,10,20,30,40,50]
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)
#output:[1,2,3,4]
now the elements in list are: [1,2,3,4]
my_list.insert(2,10)
#output:[1,2,10,3,4]
now the elements in list are:[1,2,10,3,4]
my_list.extend([5,6])
#output:[1,2,10,3,4,5,6]
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]
my_list2.pop()
#output:60
now the elements in list are: [10,20,30,40,50]
my_list2.pop(1)
print(my_list2)
#output:[10,30,40,50]
now the elements in list are: [10,30,40,50]
my_list2.remove(40)
print(my_list2)
#output:[10,30,50]
now the elements in list are: [10,30,40,50]
my_list2.clear()
print(my_list2)
#output:[]
index function will simply return index of given item
mylist2.index(40)
#output: 2
reverse will reverse the list
mylist2.reverse()
#output:[50,40,30,10]
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.