Page 292 - Computer Science Class 11 Without Functions
P. 292
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.
12.3.2 Using while loop
>>> i = 0 # using while loop
>>> while i < len(lst):
... print(lst[i],end=' ')
... i += 1
Output:
1 2 3 4 5
The variable i is initialized to 0, which is the index of the first element in the list. The while loop continues to
execute as long as the value of i is less than the length of the list. During each iteration of the loop, the current
element of the list is accessed using the index i and printed using the print() function with end=' ' to separate
the elements with a space instead of a newline. After printing the current element, the variable i is incremented by 1
to move to the next element in the list. The loop continues to execute until the value of i is equal to the length of the
list, at which point the loop terminates.
Each element of the list is printed on the same line with a space character between each element, just like in the
previous example using a for loop. However, this code achieves the same result using a while loop instead of a
for loop.
12.4 Nested Lists
A list that includes lists as its elements is called a nested list. For example, examine the list subjectCodes,
each of whose elements is itself a list.
>>> subjectCodes = [['Sanskrit', 78], ['English', 85], ['Maths', 88], ['Hindi', 90]]
>>> for code in subjectCodes:
... print(code)
...
Output:
['Sanskrit', 78]
['English', 85]
['Maths', 88]
['Hindi', 90]
>>> for code in subjectCodes:
... print(code [0])
...
Output:
Sanskrit
English
Maths
Hindi
The first for loop iterates over the elements of the list subjectCodes and prints individual elements, each of which
is a list comprising the subject name and the subject code. The second for loop iterates over the elements of the same
list subjectCodes, but prints only the first component of each element (i.e., code[0]).
290 Touchpad Computer Science-XI

