List Methods
'''
List Methods:
1.sort()
2.reverse()
3.index()
4.count()
5.copy()
6.append()
7.insert()
8.extend()
'''
#list.sort()
#This method sorts the list in ascending order and the original list is updated.
#Example:
x = [24, 9, 10, 28, 22, 18]
x.sort()
print(x) #output = [9, 10, 18, 22, 24, 28]
x.sort(reverse = True)
print(x) #output = [28, 24, 22, 18, 10, 9]
#reverse()
#This method reverses the order of the list.
#Example:
l = [1, 2, 3, 4, 5, 6, 7]
l.reverse()
print(l) #output = [7, 6, 5, 4, 3, 2, 1]
#index()
#This method returns the index of first occurrence of the list item.
#Example:
print(l.index(5)) #output = 4
print(x.index(22)) #output = 2
y = [1, 2, 3, 1, 2, 3]
print(y.index(1)) #output = 0
#If a particual element is more than one time in a list, then the occurrence of first time will be considered.
#count():
#This method returns the count of number of items with the given value.
#Example:
y1 = [1, 35, 456, 100, 671, 1, 760, 9832, 100]
print(y1.count(1)) #output = 2
print(y1.count(100)) #output = 2
#copy():
#This method returns copy of the list. This can be done to perform operations on the list without modifying the original list.
#Example:
m = y.copy()
print(y) #output = [1, 2, 3, 1, 2, 3]
m = y
m[0] = 0
print(y) #output = [0, 2, 3, 1, 2, 3]
#append():
#This method append items to the end of the existing list.
print(l) #output = [1, 2, 3, 4, 5, 6, 7]
l.append(8)
print(l) #output = [1, 2, 3, 4, 5, 6, 7, 8]
#insert()
#This method inserts an item at the given index. User has to specify index and the item to be inserted.
#Example:
x.insert(3, 26)
print(x) #output = [28, 24, 22, 26, 18, 10, 9]
y1.insert(4, 1000)
print(y1) #output = [1, 35, 456, 100, 1000, 671, 1, 760, 9832, 100]
#extend()
#This method adds an entire list or any other collection datatype(set, tuple, dictionary) to the existing list.
#Example:
a = [11, 12, 13, 14, 15]
b = [16, 17, 18, 19, 20]
a.extend(b)
print(a) #output = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
c = a + b
print(c) #output = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Comments
Post a Comment