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 (Retired) Slices Slice Functions

Kishore Kumar
Kishore Kumar
5,451 Points

Collection

Make a function named first_4 that accepts an iterable as an argument and returns the first 4 items in the iterable.

Which part of the assignment, specifically, are you having trouble with?

3 Answers

Kishore Kumar
Kishore Kumar
5,451 Points

def first_4(i): iterable = list(range(i)) return iterable[0:4]

first_4(25)

Kishore Kumar
Kishore Kumar
5,451 Points

its not working in the code challenge. throwing the error; try Again. But working fine in I-python

def first_4(i): iterable = list(range(i)) return iterable[0:4]

first_4(25) [0, 1, 2, 3]

You are attempting to create the iterable inside of the function, instead of passing it to the function like this:

def first_4(iterable):

    return iterable[0:4]


example_list = list(range(25))

first_4(example_list)

There is nothing wrong with your slicing, but the exercise is looking for you to pass an iterable into the function from the outside so that you can reuse it for any iterable that you might want the first 4 items from. Does that make sense?

C H
C H
6,587 Points

An integer is not an iterable; any list or string is, however.

def first_4(iterable):
    output = iterable[:4]
    return output

input = "Hello World"
sliced = first_4(input)
print(sliced)
#>>>Hell

input = (1, 2, 3, "hi", 4, 5, 6)
sliced = first_4(input)
print(sliced)
#>>>(1, 2, 3, "hi")