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

need help to solve this

???

slices.py
def first_4(iterable): 
    return iterable[::2][::-1]

1 Answer

Louise St. Germain
Louise St. Germain
19,424 Points

To find the first four items in an iterable (i.e., items 0, 1, 2, and 3), you only need a step size of 1 (which is the default). A step size of 2 (iterable[::2]) will give you only ever second item (which is not what you want), and a step size of -1 (iterable[::-1]) is going to go backward through the items, which is also not what you want.

Also, you're not stepping through a list of lists (if I recall correctly) so you don't need that second slice at all.

Since the first 4 items have a default start position as 0, you don't need to include it.

In my example below, it returns the first six items. See if you can figure out how to modify it to make it the first 4 items instead!

def first_6(iterable): 
    # The below is same as: return iterable[0:6:1] --> start at index 0,
    # stop just before index 6, i.e., get items at index 0, 1, 2, 3, 4, and 5,
    # and step size = 1, i.e., go forward 1 by 1.
    # Start at 0 is the default so I can be lazy and leave that out.
    # Step size of 1 is also the default so I be even more lazy 
    # and leave that out too.
    return iterable[:6:]

Have another look at the video if you are still confused. Hope this helps.