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

Dmitry Bruhanov
Dmitry Bruhanov
8,513 Points

reverse_events

def reverse_evens(iterable):
    return iterable[::-2]

print reverse_evens([1,2,3,4,5]) 
# this line was not typed in the challenge. 
#Added this to check the result in an online python compiler

This code prints out the required list: [5, 3, 1]. Why does the challenge say that it is a mistake? Maybe I misunderstood the task? Thanks in advance for you kind and swift reply.

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

def first_and_last_4(iterable):
    return first_4(iterable) + iterable[-4:]

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

def reverse_evens(iterable):
    return iterable[::-2]

2 Answers

Steven Parker
Steven Parker
229,744 Points

You're not accounting for the possibility of different list lengths.

This approach will only work on lists that have an odd number of items. If the list passed to the function has an even number of items, this will return reverse odds instead of reverse evens.

You'll either need to calculate the starting position based on the list size, or you'll need to extract the evens first and then reverse them in a separate step.

Dmitry Bruhanov
Dmitry Bruhanov
8,513 Points

Thanks for your swift reply. I checked whether the length of the iterable is even or odd and looped through the list accordingly and it worked!!!

Steven Parker
Steven Parker
229,744 Points

You don't actually need a loop, it would be better to use slices since this is a slice challenge. :wink:

Dmitry Bruhanov
Dmitry Bruhanov
8,513 Points

You got it right. By a 'loop' I meant taking every second item from the end like this:

iterable[::-2]

This is called a slice in Python, isn't it? However, since Python is built on "C" and it is only a built in function, behind the scenes this must work like a backward loop)) don't you think?

Steven Parker
Steven Parker
229,744 Points

You're probably right about what goes on in the engine, but from a programming perspective, that's simply called a "slice". So I'm guessing when you say you "looped through the list accordingly" you mean "sliced the list with different arguments". :wink: