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

first_and_last_4

I'm being asked to make a function called first_and_last_4 that returns the first and last 4 values of an iterable. I reviewed the previous videos but I can't find any information on how to return two separate bits like that. We've gone over how to start from the beginning and end where we want and how to start from the end and move backwards to return the latter part of an iterable, but I can't figure this challenge out. I tried making another indented bit under my "return list[:4]" that was "return list[-1:-5]" and I've tried commas.... Help?

slices.py
def first_4(list):
  return list[:4]
def odds(list):
  return list[1::2]
def first_and_last_4(list):
  return list[:4,-1:-5]

nevermind, guys. I figured it out. Apparently there is this handy thing called "+" ... :-P

1 Answer

Ryan Ruscett
Ryan Ruscett
23,309 Points

Hola,

You need a function that returns first four and last 4. So to me, that says. Let's get the first 4, let's get the last 4 and let's add them together.

Sometimes the videos in Python are a bit backwards. I have finished challenges where the next video discusses exactly how to do it. So skipping ahead in the videos isn't always a bad thing if you hit the challenge and don't feel you where taught what you needed.

def first_and_last_4(list):
  a = list[:4]
  b = list[-4:]
  return a + b

This does exactly that. Gets the first 4 and the last 4 and adds them together. Slicing an index only has 3 values. start, stop and step. So you need to break it into two difference sections since there isn't a start stop start stop.

Let me know if there is anything else I can help with or if you have additional questions. It can get very confusing.

Thanks!