karoks
karoks

Reputation: 31

Incorrect output of index on list elements - Python

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?

Upvotes: 1

Views: 878

Answers (4)

Akhilesh_IN
Akhilesh_IN

Reputation: 1327

as required odd index number, enumerate provides counter/index

def odd_ones_index(lst):
    total = []
    for x,i in enumerate(lst):
        if i % 2 == 1: ## checking i is odd or not
            total.append(x) ## appending index as you want index

    return total
print(odd_ones_index([1,2,3,4,5,6,7,8]))

Upvotes: 1

Mr.mb
Mr.mb

Reputation: 102

if you wont to get the odd number into your array you need to change your condition, so the code most be like that:

def odd_ones(lst):
    total = []
    for i in lst:
        if i % 2 == 0:
            total.append(i)
    return total

print(odd_ones([1,2,3,4,5,6,7,8]))

output:[2, 4, 6, 8]

Upvotes: 1

M.Shaw
M.Shaw

Reputation: 41

You want to find the odd inedx ,but what you really do is to find the odd element

for i in lst:  #(i ---->the element in lst)   
    if i % 2 == 1:

so you should try this

for i in range(len(lst)): #( i ---> the index of lst)
    if i % 2 == 1:

Upvotes: 1

Yuriy Bondaruk
Yuriy Bondaruk

Reputation: 4750

The output is correct. You iterate over the list of values and not its indices. Condition i % 2 == 1 gives following:

1 % 2 = 1 (true)
2 % 2 = 0 (false)
3 % 2 = 1 (true)
4 % 2 = 0 (false)
5 % 2 = 1 (true)
6 % 2 = 0 (false)
7 % 2 = 1 (true)
8 % 2 = 0 (false)

So the output is (1,3,5,7)

Upvotes: 1

Related Questions