List in Python | Adding item | Removing item | Length of List | Frequency of an Element |Sorting of list |Conversion from list to string
Creating list
list1 = ["first","second","Third"]
print(list1)
list2 = [1,2,3,4]
print(list2)
Accessing elements of list
We should keep in mind that first element in a list is referred as the 0th element second as 1st and so on.
X = list1[0]
Y = list2[0]
print(X)
print(Y)
Changing element value
list1[1] = "forth" #position of element is given
list2[2] = 4
Adding element in list
At last of list
list1.append("fifth")
list2.append(5)
At specific position
listname.append(position,value)
list1.insert(3,"sixth")
list2.insert(3,6)
Removing element of a list
Using list.remove()
this method remove element with its value
list1.remove("second")
list2.remove(2)
using pop() method
this method remove element at specified position.If position is not mentioned method will remove the last element.
list1.pop(2)
list2.pop(3)
list1.pop()
list2.pop()
using dlt method
this method remove element at specified position if position is not given it will delete the entire list
dlt list1[2]
dlt list2[3]
dlt list1 #deletes entire list and list will no longer exist
Getting position of element
x=list1.index("fifth")
print(x)
this method returns the position of a element.
Length of list
len(list1) method give the length of list or we can say it returns the number of element in a list
x = len(list1)
Frequency of a element in a list
Count returns the frequency of a element in a list.
list3 = [1,5,2,1,2,5,4]
x = list3.count(1)
print(x)
this will return 3 as the frequency of 1 in list is 3
y = list3.count(5)
print(y)
this will return 2 as frequency of 5 in the list is 2
Reversing a list
list3 = [1,5,2,1,2,5,4]
x = list3.reverse()
this method reverse the order of list.
Sorting of list
Sorting means arranging list in ascending or descending order
list3 = [1,5,2,1,2,5,4]
x = list3.sort()
print(x)
this will return list sorted in ascending manner.
Conversion of list to string
note that fr this conversion all element of a list should be string otherwise it will throw error.
list4 = ["h","e","l","l","o"]
X = ''.join(list4)
this will return hello in a string form.
Comments
Post a Comment