Page 190 - Information_Practice_Fliipbook_Class11
P. 190
>>> student = ['Rohan', 2304, 'B.Sc. Hons Computer Science', 9899410188, [99, 90, 85, 99, 100]]
>>> for element in student:
... print(element)
...
...
Sample Output:
Rohan
2304
B.Sc. Hons Computer Science
9899410188
[99, 90, 85, 99, 100]
Note that the list student includes three types of objects, namely, str, int, and list.
Next, we define another heterogeneous list mixedList:
>>> mixedList = [1, [2, 3], 'three', 4.0]
7.6 More Operations on Lists
● Concatenation operator + : The + operator concatenates a pair of lists. The concatenated list comprises the
elements of the first list on the left-hand side of the + operator, followed by the elements of the second list on the
right-hand side of the + operator.
>>> lst1 = ['Red', 'Green']
>>> lst2 = ['Blue']
>>> print('id(lst1): ', id(lst1))
id(lst1): 3237079561600
>>> print('id(lst2): ', id(lst2))
id(lst2): 3237079384384
>>> lst1 = lst1 + lst2
>>> lst1
['Red', 'Green', 'Blue']
>>> print('id(lst1): ', id(lst1))
id(lst1): 3237079385664
Note that the concatenation operator creates a new object for the concatenated list.
We have seen above that the assignment
lst1 = lst1 + lst2
creates a new object which is assigned to lst1. However, the Python operator += updates the existing list lst1.
For example,
>>> lst1 = [10, 5, 20]
>>> lst2 = [9, 7]
>>> print('id(lst1): ', id(lst1))
id(lst1): 3237079560384
>>> lst1 += lst2
>>> lst1
[10, 5, 20, 9, 7]
>>> print('id(lst1): ', id(lst1))
id(lst1): 3237079560384
Now we understand the concatenation of python lists, it is time to introduce the comparison operators is and is
not which are used to check whether two variables refer to the same object or not. They return True if the variables
refer to the same object and False otherwise.
When used with lists, is and is not compare the identity of the lists themselves, not their contents. That means that
two lists with the same elements are not considered the same unless they are the same object.
Here is an example:
lst1 = [10, 30, 20]
lst2 = [10, 30, 20]
176 Touchpad Informatics Practices-XI

