Social Media

1/01/2019

Some useful Functions of List data structure

There are some most important functions of list data structure which we can use in our script without knowing the internal structure of the functions.

len() function: This function will give us the length of the list.
l=[1,2,"mayank",3]
x=len(l)
print(x) # 4

index(): This method is used to find out the index of any element in the list.
The usage of this function can be as:
l=list()
l=[1,2,3,4,5]
print(l.index(3)) #2
index() method gives IndexError if we have not supplied a right index to this function.

Another usage of index() method is as:
l=[1,2,3,4]
i=l.index(2,3) # will start find index of two and searching will start from index 3
print(i)  # gives ValueError

reverse() function:  This function will reverse the element of the whole list.
l=[1,2,3]
l.reverse()
print(l) # [3,2,1]

sort() function: This method is used to sort the given list.
l=[2,5,1,4,6,2]
l.sort()
print(l) # [1,2,2,4,5,6]

clear() function: This function is used to delete all elements from the list.
The usage of this function is as follows:
l=[1,2,3,4]
l.clear()
print(l) #[]

max() function: This function returns the maximum value from the given list.
A simple script to demonstrate this function is as:
l=[2,3,5,2,6,6,4]
m=max(l)
print(m) #6

min() function: This function returns the maximum element from the list.
The script can be as:
l=[1,2,,5,2,5]
m=min(l)
print(m) #1

sum() function: This method returns the sum of all values present in the list.
example:
l=[1,2,3,4]
s=sum(l)
print(s) #10


Be First to Post Comment !
Post a Comment