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

Slice functions - task 3 of 3

Not sure how to combine and return multiple slices of a list

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

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

def first_and_last_4(itb):
  return itb[0:4 and -4:]

3 Answers

Andrew Winkler
Andrew Winkler
37,739 Points

You almost got it. Remember concatenation? Use it.

def first_and_last_4(itb):
  return itb[:4] + itb[-4:]
Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

There are a few way to do this. One is to add the second slice to the first:

def first_and_last_4(itb):
    result = itb[0:4]
    result.extend(itb[-4:])
    return result
Alex Calder
Alex Calder
1,110 Points

Why does this not work?

return z[0:4].extend(z[-4:])
Chris Freeman
Chris Freeman
Treehouse Moderator 68,454 Points

This does not work due to two elements.

:arrow_right: the partial result from z[0:4] is stored in a temporary variable.

:arrow_right: the extend() method operates "in place" on an object and returns None

Therefore, the compound statement value is None which is what is returned by the function return.