Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Slices Slice Functions

Madhan Mohan Reddy Paidimarla
Madhan Mohan Reddy Paidimarla
9,484 Points

create a function named first_4 that returns the first four items from whatever iterable is given to it.

create a function named first_4 that returns the first four items from whatever iterable is given to it.

slices.py
first_4 = 1,2,3,4

try def first_4(num): return num[0:4]

1 Answer

James Arnold
James Arnold
3,974 Points

First thing, it's asking us to create a function instead of a just a variable like what we have here. To create a function we'll use:

def first_4(ctx):
    return

So now that we have our function defined and we're passing in our value - ctx. We need to define the function to slice off the first four elements. This can be done using list slicing like so:

def first_4(ctx):
    return ctx[:4]