Operations on Python Lists
It is possible to perform operations like addition, multiplication and searching on Python Lists.Addition Operation on Python Lists
Addition operation on Lists is possible using + operator:
>>> list1 = [1, 2]
>>> list1
[1, 2]
>>> list2 = [3, 4]
>>> list2
[3, 4]
>>> list1 + list2
[1, 2, 3, 4]
>>> list1
[1, 2]
>>> list2 = [3, 4]
>>> list2
[3, 4]
>>> list1 + list2
[1, 2, 3, 4]
Multiplication Operation on Python Lists
Multiplication operation on Lists is possible using * operator:
>>> mylist = [1, 2]
>>> mylist
[1, 2]
>>> mylist * 3
[1, 2, 1, 2, 1, 2]
>>> mylist
[1, 2]
>>> mylist * 3
[1, 2, 1, 2, 1, 2]
Note: The + and * operations do not modify the list. The original list will remain same even after use of + and * symbols on it.
Search operation in Python Lists
in keyword can be used to search an element in the given list.
>>> insurance = ['sbi', 'icici', 'hdfc', 'hsbc']
>>> insurance
['sbi', 'icici', 'hdfc', 'hsbc']
>>> 'sbi' in insurance
True
>>> 'seas' in insurance
False
>>> insurance
['sbi', 'icici', 'hdfc', 'hsbc']
>>> 'sbi' in insurance
True
>>> 'seas' in insurance
False
Assignment operation to Slices
Use of assignment operator to slices is possible. It can even change the size of the list or clear it entirely:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
# replace some values of lists
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> letters[:] = []
>>> letters
[]
No comments:
Post a Comment