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

james mchugh
james mchugh
6,234 Points

create a function

I'm trying to create a function that returns the first 4 items given to it. I've tried many ways and can't get it.

slices.py
items = []
def first_4():
    for item in items:
    four_items = items[:3]
        first_4()

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

This is a classic slicing problem. You can get the first four elements in several ways. They intend for you to understand the colon slicing operation.

data[start_element : end_element : optional_step_count]

Below is a "cookbook approach" you can use:

To get the first three elements, either start at 0 or leave it blank (the default is 0)

data[0:3] or data[:3]

To get the last three elements, start three elements from the end and go to the end. The first way is the least complicated.

data[-3:] or data[len(data)-3:] or data[len(data)-3:len(data)]

To get even elements, start at 0, step by 2

data[::2] or data[0::2]

To get odd elements, start at 1, step by 2

data[1::2]

To get the reverse of a list (sort of a tricky approach), start at the end and step backward by -1

data[::-1]

They just want you to write the functions, so you don't need to iterate though a list in the exercise. Here is what you'd write to get the first four elements.

--- SPOILER ALERT---

def first_4(data):
    return data[:4]
james mchugh
james mchugh
6,234 Points

Jeff, Thank you for your explanation. You made it much simple than I was trying to make it.