Odd Indices

Hello,

im stuck at this excercise: .

Create a function named odd_indices() that has one parameter named lst .

The function should create a new empty list and add every element from lst that has an odd index. The function should then return this new list.

For example, odd_indices([4, 3, 7, 10, 11, -2]) should return the list [3, 10, -2] .

My solution is this:

def odd_indices(lst):

new_list =

i = 0

while i < len(lst) and i % 2 != 0:

new_list.append(lst[index]) 

i += 1

return new_list

#Uncomment the line below when your function is done

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

Why doesnt it work ?

LG

Hi @zoku86, welcome to the forums :slightly_smiling_face:

What error do you get? Analyzing your error can be really useful for finding where you went wrong.

1 Like

I get a list with nothing in it out…
I dont know if there is something logically wrong

Hi @zoku86 welcome to the forums!

Could you paste again and press the format </> button before pasting your code?
Indentation sometimes matters in these cases and can affect how your code runs.

Thank being said there’s a couple of potential issues in the code

new_list = []
i=0
while i < len(lst) and i % 2 != 0:
    new_list.append(lst[index]) 
    i += 1
    return new_list

How does a while loop work? What happens when the conditions aren’t met? That’s problem 1.

Problem 2 is index isn’t defined, from where I see it. Unless I’m missing something.

Problem 3 is not really a problem but a consideration, a while-loop could work for this, but other loop types might make more sense (and cost less space/memory). With a while-loop we do need a counter (unless you use .pop() or something), is there a way to use a loop without a counter?

5 Likes