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])
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.
Related Questions
What will be the output of the following statement?
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list1[::-2] list1[:3] + list1[3:]What will be the output of the following statement?
list1 = [1, 2, 3, 4, 5] list1[len(list1)-1]What will be the output of the following code segment?
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] del myList[3:] print(myList)What will be the output of the following code segment?
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] del myList[:5] print(myList)