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

Slices

Quiz challenge: Make a new function named first_and_last_4. It'll accept a single iterable but, this time, it'll return the first four and last four items as a single value.

Here's my code:

def first_and_last_4(two):
      three = two[:5]
      four = two[-4:]
      five = three + four
      return five
slices.py
def first_4(one):
    return one[:4]

def first_and_last_4(two):
    three = two[:5]
    four = two[-4:]
    five = three + four
    return five

1 Answer

Paul Harrison
Paul Harrison
5,533 Points

Hey Idris -

The only issue with the code is your "three" variable, where you have it pulling the first 5 characters instead of the first 4. Remember, it starts counting at 0.

def first_and_last_4(two):
    three = two[:4]
    four = two[-4:]
    five = three + four
    return five

Alternatively, this can be simplified to:

def first_and_last_4(x):
    return x[:4] + x[-4:]

Thank you Paul. That was a careful observation.