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!

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 tried to remove the odds

Hi,

I'm having trouble in the last function, I'm trying to remove the odds so I can return only the evens in reverse.

At first I tried like this : return no_odds[::-2]

but a mate told me I was returning the odds, so it would be better to remove them. Please somebody help me solve this problem

Thanks a bunch!

slices.py
def first_4(iterable):
    return iterable[:4]

def first_and_last_4(ite):

    head = ite[:4]
    tail = ite[-4:]

    concat = head + tail
    return concat

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

def reverse_evens(iterable):

    #removing the odds
        # returning a variable with the odds
        odds_remove = return iterable[::2]

        # removing that variable from list
        no_odds = iterable.remove(odds_remove)

    return no_odds[::-1]

2 Answers

Keenan Johnson
Keenan Johnson
13,841 Points

For the last function what you're aiming to do is to first get all of the elements in even numbered positions, and then reverse that list. In your solution, you want to remove that return statement and starting from the beginning (the 0th element), get every other element. The way you're using to reverse [::-1] will work perfectly here. Hope this helps!

Solution:

def first_4(iterable):
    return iterable[:4]

def first_and_last_4(iterable):
    firstFour = iterable[:4]
    lastFour = iterable[-4:]
    return firstFour + lastFour

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

def reverse_evens(iterable):
    evenIterables = iterable[0:][::2]
    return evenIterables[::-1]
Steven Parker
Steven Parker
225,664 Points

:information_source: FYI: making a slice using "[0:]" doesn't do anything except duplicate the array, which isn't needed if you're going to immediately apply another slice.

Keenan Johnson
Keenan Johnson
13,841 Points

Good catch on that Steven and thanks!

Hi Keenan, your explanation was great, I knew I had to define the starting position but I had no ideia how.

Thank you so much :)

Steven Parker
Steven Parker
225,664 Points

You have a few issues:

  • you cant use return in an assignment statement
  • if you give remove a list, it will only remove the entire list if it is a sub-item of the main list
  • instead of trying to remove the odds, why not use a slice to return only the evens?