Home > Back-end >  """Q6) Use a loop to display elements from a given list present at odd index position
"""Q6) Use a loop to display elements from a given list present at odd index position

Time:12-05

"""Q6) Use a loop to display elements from a given list present at odd index positions. my_list=[10 ,20 ,30 ,40 ,50 ,60 ,70 ,80 ,90 ,100]"""

CodePudding user response:

for i in range(len(list)):
    if i % 2 == 1:
        print(list[i])

Basically this loops through the numbers corresponding to the list (that's what range(len(list)) does) for example ['a','b','c'] would become range(len(['a','b','c'])) which is range(3) which is [0,1,2]. The modulo operator '%' checks remainder of division (so 2 % 2 == 1 would return false whereas 1 % 2 == 1 would return true. Basically to check for odd numbers)

CodePudding user response:

you can use enumerate() function.

for i,e in enumerate(my_list):
    if i%2 != 0:
        print(e)
  • Related