Welcome to the Treehouse Community
Looking to learn something new?
james mchugh6,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.
items =  def first_4(): for item in items: four_items = items[:3] first_4()
Jeff MudayTreehouse 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
To get the reverse of a list (sort of a tricky approach), start at the end and step backward by -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]