FAQ: Code Challenge: Loops - Odd Indices

Thanks for your answer. Sorry that I for got the formatting.
The formatting is not the problem.
When I run the function the output is just for.
It seems as if the if-loop does not check all items in (lst).

I meant that it’s hard for anyone reading your code to tell exactly what’s wrong. Indentation is used to group code blocks together in Python so I expect it’s an indentation issue which is causing your function to return early.

A print statement or several in the loop would help you to determine how many times your loop actually gets performed. It’s also an easy way to determine what happens at each step which makes it easier to diagnose problems that you cannot spiot by reading the code.

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

That is the code as I have entered it.
Output from print is “[4]”.

Does that help?
Sorry for the irritations, I am new :slight_smile:

The length of that returned list is due to the indentation. Remember that return exits a function once executed. Perhaps adding the following line to your code will help you to see what’s happening-

def odd_indices(lst):
    odd_indices = [ ]
    for i in lst:
        # using a proper counter might be nicer but this example is short enough not to
        print(i)  # continue from here as before

It’s also worth noting that the value returned is not at an odd index (note that Python indexing begins at zero). My previous comments might help you work out why.

1 Like

Why do I receive only part of the answer (and therefore an incorrect answer) with my attempted code?

#Write your function here
def odd_indices(lst):
newlist =
for num in lst:
newlist.append(lst[1])
lst.remove(lst[0])
lst.remove(lst[0])
return newlist

#Uncomment the line below when your function is done
print(odd_indices([4, 3, 7, 10, 11, -2]))

I get 3 and 10, rather than 3, 10 and -2.

It’s generally a bad idea to alter the object you’re iterating over since it so often results in unusual behaviour. If you wanted to work out what’s going on, why not throw in some print statements after each step to see what’s changing.

It’d also be worth having a quick look through this guide on code formatting as it makes code much easier to read-

On a more general note I’d be very careful about altering global objects inside a function at any time. It’s rarely necessary and if the main purpose of your funciton is to do so make sure it’s very obvious this is the case since it can obscure what’s happening for whoever looks at the code (which can often include yourself at a later date).

1 Like

A shorter version

def odd_indices(lst):
new_list = [lst[i] for i in range(len(lst)) if i % 2 != 0]
return new_list

1 Like

This would also work:

def odd_indices(lst):
  new_list = [lst[i] for i in range(1, len(lst), 2)]
return new_list

When we use range we don’t need a comprehension, just cast the range object as a list.

list(range(...))

As a comprehension we can use the spread operator…

[*range(...)]
1 Like

Where can I get more problems like this to work on. I need to write and problem solve through more questions like this to understand it.

For now, work on understanding all the in’s and out’s of range(). Create a whole plethora of different sequences using the one function. See if you can predict the outcome before running the code. Test yourself in this way so that you begin to spot things.

Sounds good. I find it easy to just cruise through each section. But without repetition I don’t understand it completely.

1 Like

There is a reason this takes months and years to fully learn… It’s a lot to take in, there are endless nuances, hills and curves, and cliffs. We did not learn to talk in a week or a month. Treat programming along the same timeline and respect that it is not something we breeze through. Review, repeat, redo, and practice, practice, practice. When you’re not doing that, read the docs, articles about concepts, explore and experiment extensively with each new concept.

As we progress we are adding to our tool chest, granted, but we cannot add to our brain trust without a massive amount of repetition and introspection. Learn the basics backwards and forwards, up and down, left and right. Don’t overlook anything, and never assume that you are done learning.

Happy coding!

Hi, i am new to coding and i am wondering if someone can explain to me why doesn’t this code work?

#Write your function here
def odd_indices(lst):
  new_lst = []
  for index in lst:
    if lst[index] % 2 != 0:
      return new_lst.append(lst[index])


#Uncomment the line below when your function is done
print(odd_indices([4, 3, 7, 10, 11, -2]))

Two things are wrong here. return within a loop terminates the function; and, .append() has no return value. We are not returning the appended list, only None.

Remove the return from within your loop and write it outside of the for loop (at the very end).

return new_lst

Thank you for responding so quickly. I removed it outside of the for loop like this:

#Write your function here
def odd_indices(lst):
  new_lst = []
  for index in lst:
    if lst[index] % 2 != 0:
      new_lst.append(lst[index])
  return new_lst
      

#Uncomment the line below when your function is done
print(odd_indices([4, 3, 7, 10, 11, -2]))

but i got the IndexError: list index out of range

To access the list by index use,

for index in range(len(lst)):

OK so this is not in the spirit of learning how to use loops and indices, but it is also possible to solve this challenge with slicing using the step parameter.

def odd_indices(lst):
  return lst[1::2]

This returns a slice of the original list which starts at the first odd index (1) and goes to the end of the list in steps of 2.

Hi guys,

the answer of this exercise says “Another way to do this would be to iterate through all indices and use an if statement to see if the index you’re currently looking at is odd.”

Well that is what I was trying to do, but the code doesn’t print anything.

Any clue why please?

def odd_values(lst):
    new_lst = []
    for i in lst:
        if lst.index(i) % 2 != 0:
            new_lst.append(lst[i])
    return new_lst

print(odd_values([4, 3, 7, 10, 11, -2]))

i is the index. The above is looking for i in the list.

if i ...