List
As discussed in previous blog, the list is container which is mutable i.e. the elements in the list can be modified, added or deleted, etc.
Let the given list is
L = [1, 4, "Arjun"]
print(L)
Output>>>
[1, 4, 'Arjun']
To add element in the list following:
L = L.append("Karna")
print(L)
Output>>>
[1, 4, 'Arjun', 'karna']
Typically, element is added in the last. To insert element at any specific index number, do following:
L=[1, 4, 'Arjun', 'Karna']
L.insert(2,'Dronacharya')
print(L)
Output>>>
[1, 4, 'Dronachayra', 'Arjun', 'Karna']
To delete specific element from the list, do following:L.remove("Arjun")
print(L)
Output>>>
[1, 4, 'Karna']
To remove last element from of the list, do following:
L=[1, 4, 'Arjun', 'Karna']
L.pop()
print(L)
Output>>>
[1, 4, 'Arjun']
To clear all the element from the list, do following:
L=[1, 4, 'Arjun', 'Karna']
L.clear()
Output>>>
[]
To delete the whole list including container, do following:
L=[1,4,'Arjun','Karna']
del(L)
print(L) #get error as L is not existing now. ðŸ’
To copy content of one list to another list
L1 = [1,4,"Arjun", "Karna"]
print(L1)
L2 = L1.copy()
print(L2)
L1.append("Dronacharya")
print(L1)
print(L2)
Output>>>
[1,4, "Arjun", "Karna"] [1,4, "Arjun", "Karna"] [1,4, "Arjun", "Karna", "Dronacharya"] [1,4, "Arjun", "Karna"]
If we use L2=L1, L2 will create only reference of L1 (nothing else) and all the changes made in L1 will be reflected in L2 i.e. L2 will be dependent on L1 that we don't require everytime.
L1=[1,4, "Arjun", "Karna"]
L2=list1 L1.append("Dronacharya") print(L1) print(L2)
Output>>>
[1,4, "Arjun", "Karna", "Dronacharya"]
[1,4, "Arjun", "Karna", "Dronacharya"]
To concatenate two strings
L1 = ["Ram", "Shyam", "Mohan"]
L2 = [10, 20, 30]
L3 = L1 + L2
print(L3)
Output>>>
['Ram', 'Shyam', 'Mohan', 10, 20, 30]
or, we can do concatenation of two lists using for loop also, as follows:
L1 = ["Ram", "Shyam", "Mohan"]
L2 = [10, 20, 30]
for index in L2:
L1.append(index)
print(L1)
Output>>>
['Ram', 'Shyam', 'Mohan', 10, 20, 30]
or, we can do the concatenation two lists using extend funciton:
L1 = ["Ram", "Shyam", "Mohan"]
L2 = [10, 20, 30]
L1.extend(L2)
print(L1)
Output>>>
['Ram', 'Shyam', 'Mohan', 10, 20, 30]
To sort the elements of the given list, do following:
L1 = ["Ram", "Shyam", "Mohan"]
L1.sort()
print(L1)
Output>>>
['Mohan', 'Ram', 'Shyam']
To count total number of items of similar type, do following:
L1 = ["Ram", "Shyam" , "Mohan", 'Ram']
print(L1.count("Ram"))
Output>>>
2
To count total number of items in list:
L1 = ["Ram", "Shyam" , "Mohan", 'Ram']
print(len(L1))
Output>>>
4
To count length of each and every item in list:
L1 = ["Ram", "Shyam" , "Mohan", 'Ram']
for index in L1:
print(len(index))
Output>>>
3 5 5 3
No comments:
Post a Comment