Informatics Practices

What will be the output of the following code segment?

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(0, len(myList)):
   if i % 2 == 0:
      print (myList[i])

Python List Manipulation

4 Likes

Answer

1
3
5
7
9

Working

In the given code, myList is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The for loop iterates over the range of indices from 0 to len(myList)-1. Inside the loop, the if statement checks if the current index i is even by using the modulus operator i % 2 == 0. If the condition is true (i.e., the index is even), it prints the element at that index in myList. As a result, the code prints all the elements at even indices, specifically: 1, 3, 5, 7, and 9.

Answered By

1 Like


Related Questions