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

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 27,510 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.