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 (Retired) Slices Slice Functions

Andy Bosco
PLUS
Andy Bosco
Courses Plus Student 681 Points

returns the first 4 and last 4 items in the iterable

This is challenging and so far I can't find anything on Google for Slicing the "first 4 and last 4 items in the iterable." What am I doing wrong?

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

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

def first_and_last_4(filter):
  return filter[3:-3:]

1 Answer

Michael Norman
PLUS
Michael Norman
Courses Plus Student 9,399 Points

In the first part of the challenge you did first_4, so that part is complete. All we really need to worry about now is the last 4. You may remember that when we want the item at the end of a list, say my_list, can user

my_list[-1] # last element
my_list[-2] # next to last element

Using negative indices we can get the forth element from the end using an index of -4 and continue to the end of the list using a colon as before. Since lists are mutable we can concatenate the two and return that answer

def first_and_last_4(filter):
  return first_4(filter) + filter[-4:]
Andy Bosco
Andy Bosco
Courses Plus Student 681 Points

Thank you. I didn't know you can add the List together. Now I know.