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

Madhan Mohan Reddy Paidimarla
Madhan Mohan Reddy Paidimarla
6,936 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,969 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]