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 trialJon Gaspar
656 Points"Make a function named list_4 that accepts an iterable as an argument and returns the first 4 items in the iterable"
Loving the course so far but can't seem to figure this one out. I tried making a list and using the slice [0:4] thing but that didn't work, then I tried using a 'for' loop which also didn't work, than I tried defining an iterable class (not that I really know that is) but no avail there either.
Any tips? thanks in advance
1 Answer
Evan Demaris
64,262 PointsI'm not sure what went wrong with the slice - it helps if you post your code so we can guide you!
That said, you can define your function with a slice as;
def first_four(iterable):
return iterable[0:4]
Bare in mind for the second and third parts of this challenge;
[a:b:c]
a
is the start, b
is the stop, c
is the step. You can step backwards with a negative c
, you can start so many indexes from the end of a list with a negative a
, and you can add slices to each other with a +
operator to make a new list from multiple slices of an existing list.