Page 188 - Information_Practice_Fliipbook_Class11
P. 188

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 7.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 7.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 7.1).


        7.3 Traversing a List

        We can traverse a list by iterating over each element of the list using a for loop or while loop.
        1. Using for loop
            lst = [1, 2, 3, 4, 5]
            for element in lst:                            # using for loop
                    print(element,end=' ')
            Sample Output:

            1 2 3 4 5
        In the above example, lst is a list of elements. The for loop iterates over each element of the list one by one.
        During each iteration, the current element of the list is assigned to the variable element. The loop body then executes
        the print() function with the current element as its argument.
        The end=' ' argument in the print() function tells Python to append a space character to the end of each printed
        element instead of a newline character. This means that all the elements will be printed on the same line with a space
        between each element.




          174  Touchpad Informatics Practices-XI
   183   184   185   186   187   188   189   190   191   192   193