I just started to study Python and I am stuck at this one.
basically I would like to find out the add numbers in the odd index number.
here is my code.
def odd_ones(lst):
total = []
for i in lst:
if i % 2 == 1:
total.append(i)
return total
print(odd_ones([1,2,3,4,5,6,7,8]))
Output is
[1, 3, 5, 7] instead of [2, 4, 6, 8]
can someone please help me with this?
for i in lstis iterating over the elements, not the indices. You needfor i, x in enumerate(lst): if i % 2 == 1: total.append(x)for i in range(len(lst))would be enough.lstandfor i in range(len(lst)): # anything with lst[i]is a huge code smell.for i, _would be bad practice. Wait... I think you edited?for i, x in enumerate(lst)looks good enough. If that was what you wrote in the first place, my apologies.