Page 339 - Computer Science Class 11 With Functions
P. 339
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 13.3: 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 13.3, 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 13.3).
13.2 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
01 lst = [1, 2, 3, 4, 5]
02 for element in lst: # using for loop
03 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.
2. Using while loop
01 lst = [1, 2, 3, 4, 5]
02 i = 0 # using while loop
03 while i < len(lst):
04 print(lst[i],end=' ')
05 i += 1
Sample Output:
1 2 3 4 5
Lists and Tuples 337

