1

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?

6
  • 2
    for i in lst is iterating over the elements, not the indices. You need for i, x in enumerate(lst): if i % 2 == 1: total.append(x) Commented Mar 19, 2019 at 3:35
  • for i in range(len(lst)) would be enough. Commented Mar 19, 2019 at 3:37
  • 1
    @Taegyung except then you have to index into lst and for i in range(len(lst)): # anything with lst[i] is a huge code smell. Commented Mar 19, 2019 at 3:38
  • @AdamSmith then writing 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. Commented Mar 19, 2019 at 3:40
  • your output will be [0, 2, 4, 6] not [2, 4, 6, 8] Commented Mar 19, 2019 at 3:48

4 Answers 4

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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:

Comments

1

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]

Comments

1

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]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.