Page 291 - Computer Science Class 11 Without Functions
P. 291

A list assignment does not create a new copy of the list. Instead, on the execution of the assignment statement, the
            variable on the left-hand side of the assignment statement refers to the list on the right-hand side of the assignment
            statement; for example,
             >>> colors
                 ['red', 'green', 'blue',]
             >>> colorsRef = colors
             >>> id(colors)
                 1777056884928
             >>> id(colorsRef)
                 1777056884928
            Note that the variables colors and colorsRef refer to the same list of objects having the id: 1777056884928.
            Variables that refer to the same object are called aliases of each other. Thus, each of the variables colors and
            colorsRef is an alias of the other.












            As the variables colors and colorsRef refer to the same list, changes made to the list, named colorsRef, are
            reflected in the list, as illustrated below:























               Fig 12.1: As the names colorsRef and colors are aliases of each other, either of these names may be used to modify
                                                             the list.

            On execution of line 3 in Fig 12.1, the value at index 1 in the list colorsRef is updated to 'yellow'. The modification
            gets reflected again, when we print the list colors (line 4) as each of the variables colorsRef and colors refers
            to the list object (see Fig 12.1) .


            12.3 Traversing a List

            We can traverse a list by iterating over each element of the list using a for loop or while loop.
            12.3.1 Using for loop

             >>> lst = [1, 2, 3, 4, 5]
             ... for element in lst:  # using for loop
             ...     print(element,end=' ')

            Output:
                 1 2 3 4 5


                                                                                                Lists and Tuples  289
   286   287   288   289   290   291   292   293   294   295   296