Page 293 - Computer Science Class 11 Without Functions
P. 293
12.5 Heterogeneous List
The items stored in the list can be of any type, such as numeric, string, Boolean, or list. For instance, a list comprising
student details, namely name, roll number, course, contact number, and marks in five subjects may be specified as follows:
>>> student = ['Rohan', 2304, 'B.Sc. Hons Computer Science', 9899410188, [99, 90, 85, 99, 100]]
>>> for element in student:
... print(element)
...
...
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]
12.6 More Operations on Lists
12.6.1 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.
Lists and Tuples 291

