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

JC Canapi
JC Canapi
2,097 Points

Slice Functions challenge task 2 of 4

I am trying to complete the challenge task 2 of 4. I seem to get the right answer when I try in workspaces but the challenge won't be accept my answer.

May I know what am I doing wrong here?

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


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

Hey

you cannot run through a list backwards. (from the last to penultimate to ...) but you can start from position 'fourth from last' and then run through to the end. That did the trick for me at least.

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! First, the comment left by Media Markt is not correct. It is absolutely possible to go through a list backwards. This can be done by simply doing list[::-1], but based on your current code, I would guess that you already know that.

I feel like there might be a misunderstanding of the instructions. When I run your code and pass in "Treehouse", I get back "Treeesuo", but I would expect to get back "Treeouse". You're getting the first 4 and the last 4, but you've got the last 4 parts in the backwards order.

To get the last 4 of an iterable with a slice going in a forwards order, I would write list[-4::].

Hope this helps! :sparkles:

ok, I should have specified: you cannot go through a list backwards using the method [-1: -5]

JC Canapi
JC Canapi
2,097 Points

Thank you very much! This has helped me so much. :)