Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Slices Slice Functions

I don't know what is wrong with my code

Now I am supposed to be returning the letters or the numbers from an iterable . I don't find a better way to do it instead of making a list an inserting the elements in the list and then to return the list. The problem is that the provided iterable is unknown is it a string a list or a number.

slices.py
def first_4(iterable):
    return iterable[:4]
def first_and_last_4(iterable):
    new_iterable= iterable[:4] + iterable[-4:]
    return new_iterable
def odds(iterable):
    index = 1
    odd_iterable = []
    for letter in iterable :
        if letter = iterable[index]:
            odd_iterable.insert(letter)
        index = index + 2
    return odd_iterable

sorry I am supposed to be returning the elements with odd indexes only

1 Answer

Casper Koch
Casper Koch
5,375 Points

There is multiple things wrong with your code.

Your code won't work because you have an index problem. in your code you plus the index variable with 2 everytime Python runs the for loop. If the given iterable has a length of 2, you will get an index error the second time Python runs the for loop, because at that time your index variable value will be 3, and a list with 2 items does not have an index of 3.

And now that, you are practising slicing, it would be a fantastic idea to use slicing. You could try something like

def odds(iterable): return iterable[1::2]