BlogsDope image BlogsDope

Functions we can use on a Python's list

May 19, 2017 PYTHON ARRAY EXAMPLE FUNCTION 7810

This article is an extension of the ‘Make a list’ chapter of Python. If you need to learn basics then visit the Python course first. You can also practice a good number of questions from practice section.

append


Appends list with an item or adds an item at the end of the list.

a = [1, 2, 3,]
a.append(4) # a --> [1, 2, ,3 4]

count


Counts the number of times an element is appearing in a list.

a = [1, 2, 3, 2, 2]
a.count(2) # 3

extend


Adds a list to another list

a = [1, 2, 3]
b = [4, 5]
a.extend(b) # a --> [1 ,2, 3, 4, 5]

index


Gives the index of the first appearance of an element in a list.

a = [1, 2, 2, 3]
a.index(2) # 1

insert


Inserts an element at a given position

a = [1, 2, 3, 4]
a.insert(1,5) # a --> [1, 5, 2, 3, 4] 

max


Gives an element which has the maximum value.

a = [1, 2, 3, 4, 56, 9]
max(a) #56

min


Gives an element which has the minimum value.

a = [1, 2, 3, 4, 56, 9]
min(a) #1

pop


Removes and returns an element at a given position. If no position is specified then it removes and returns the last element.

a = [1, 2, 3, 4, 5, 6]
a.pop(1) # 2
a.pop() # 6

remove


Removes the first element whose value is matched with the given value.

a = [1, 2, 3]
a.remove(1) # a --> [2, 3]

reverse


Reverses a list.

a = [1, 2, 3, 4]
a.reverse() # a --> [4, 3, 2, 1]

sort


Arranges the elements of a list in ascending order.

a = [3, 4, 1, 2]
a.sort() # a --> [1, 2, 3, 4]

 


Liked the post?
Developer and founder of CodesDope.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).