List Operations and Methods
Operation related to the list are shown in the table below where the operators + and * are used to concatenation and for the repetition of the value.
for example:
| Python Expression | Results | Description |
|---|---|---|
| len([4,5,6]) | 3 | Returns Length |
| [1, 2, 3] + [4, 5, 6,7,8] | [1, 2, 3, 4, 5, 6,7,8] | Perform Concatenation |
| [‘Ravi’] * 4 | [‘Ravi, ‘Ravi’, ‘Ravi’, ‘Ravi’] | Perform Repetition Of value |
| 1 in [1, 2, 3] | True | Membership |
| for x in [1, 2, 3,4,5,6,7]: print x, | 1 2 3 4 5 6 7 | Perform Iteration |
In build method in python:
Python include following method by which work becomes easier:
1.len()
This method return the number of elements in the list.
#len() method count the number of elements
list1ls =[6, 'abcd'], list2ls = [13, 'xyza', 'bzara']
print ("First list length : ", len(list1ls))
print ("Second list length : ", len(list2ls))
2.max()
This method will return the maximum value element form the list.
#max() method will return max value from list
list1ls, list2ls = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print ("Max value element of list : ", max(list1ls))
print ("Max value element of list: ", max(list2ls))
3.min()
This method will return the min value element form the list.
#min() method will return min value from list
list1ls, list2 = [123, 'df', 'ara', 'abcc'], [4456, 3700, 2200]
print ("Max value element form list1 : ", max(list1ls)
)
print ("Max value element form list2: ", max(list2ls))
4.list()
This method will convert tuple type to list type
#list() will convert tuple from list
Anum1 = (123, 'xyz', 'zara', 'abc');
Bnum2 = list(Anum1)
print ("List elements are : ", Bnum2)
5.cmp()
This method will compare two list and return -1, 0 ,1:
if a<b
return -1
if a=b
return 0
if a>b
return 1
# Python program to demonstrate the cmp() method comparison
# when a<b
a = 1
2
b = 2
2
print(cmp(a, b))
# when a = b
a = 23
b = 2
3
print(cmp(a, b))
# when a>b
a = 3
2
b = 2
1
print(cmp(a, b))
