List Operations using operators:
- Lists can be concatenated using + operator. List repetition is possible using * operator.
- “in” operator is used to test whether the element is present or not in the list.
- “in” operator can be used to iterate the list using ‘for’ loop.
- “not in” operator can be used to check whether the element is not present or not in the List.
Code:
print("List operations using operators :")
a1 = [1,2,3]
a2 = [4,5,6]
print("a1 list :", a1)
print("a2 list :", a2)
print("a1=a1+a2 :")
a1=a1+a2
print("a1 list :", a1)
print("a2 list :", a2)
print("a2=a2*3 :")
a2 = a2*3
print("a2 list :", a2)
print("a1 list :", a1)
print("5 is present :", 5 in a1)
print("7 is present :", 7 in a1)
print("20 is not present :", 20 not in a1)
print("6 is not present :", 6 not in a1)
Output:
List operations using operators :
a1 list : [1, 2, 3]
a2 list : [4, 5, 6]
a1=a1+a2 :
a1 list : [1, 2, 3, 4, 5, 6]
a2 list : [4, 5, 6]
a2=a2*3 :
a2 list : [4, 5, 6, 4, 5, 6, 4, 5, 6]
a1 list : [1, 2, 3, 4, 5, 6]
5 is present : True
7 is present : False
20 is not present : True
6 is not present : False
sort():
- sort all elements in the specified list
- All elements in the list should be of same type
- Heterogeneous elements list cannot sort.
Code:
a1 = [10, 40, 20, 50, 30]
print("a1 List is :",a1)
a1.sort()
print("Sorted a1 list is :", a1)
a2 = [34.56, 23, "abc"]
print("a2 List is :",a2)
a2.sort() # sorting possible only on homogenous data elements
print("Sorted a2 list is :", a2)
Output:
a1 List is : [10, 40, 20, 50, 30]
Sorted a1 list is : [10, 20, 30, 40, 50]
a2 List is : [34.56, 23, 'abc']
TypeError: '<' not supported between instances of 'str' and 'int'
reverse():
- Reverse the elements in specified list.
Code:
a1 = [10, 40, 20, 50, 30]
print("a1 List is :",a1)
a1.reverse()
print("Reversed a1 list is :", a1)
a2 = [34.56, 23, "abc"]
print("a2 List is :",a2)
a2.reverse()
print("Reversed a2 list is :", a2)