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

vietnaums hollow
vietnaums hollow
5,108 Points

task four

this runs: _in workspaces _with different length lists _even or odd indexes __[-1::-2] or [-2::-2] __including or excluding zed _____including positives and negatives

maybe one of you know an eventual flaw in logic with this i dont see why it cant be ONE line of code so if you have a solution to this , keep that in mind

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

def first_and_last_4(y):
    y = y[:4] + y[-4:]
    return y

def odds(x):
    x = x[1::2]
    return x

def reverse_evens(w):
    w = w[-1::-2]
    return w
vietnaums hollow
vietnaums hollow
5,108 Points

apologize for the punctuation . didnt know itd all come out in-line .

3 Answers

Stuart Wright
Stuart Wright
41,119 Points

Well, it is possible in one line. It's just not possible in one slice operation. That's because you need to first extract only the even index numbers, then reverse them. These slice operations each require you to complete the 'step' number (the last number) - first 2 to filter for even numbers, then -1 to reverse.

def reverse_evens(w):
    w = w[::2][::-1]
    return w

Personally I would still use two lines to make the code more readable:

def reverse_evens(w):
    evens = w[::2]
    reverse = evens[::-1]
    return reverse
vietnaums hollow
vietnaums hollow
5,108 Points

so logically it works , but for claritys sake : sacrifice efficiency ?

Stuart Wright
Stuart Wright
41,119 Points

Exactly. It's a matter of opinion of course, but especially if somebody else will be working on your code at some point, I would consider the second solution better.