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

Sergei Miroshnikov
Sergei Miroshnikov
3,313 Points

Bummer! Try again! This is amazing error message ! Please explain why my solution is not valid ...

def first_4(iterable):
    result = []
    for i in (range(0, iterable)):
        result.append(i)
        if i == 3:
            break
    return result

I have tried another function I wrote

def first_4(iterable):
    result = []
    for i in range(0, iterable):
        result.append(i)
    return result[:4]

2 Answers

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

I made a few tweaks to your code to make it work.

  • We can't put an iterable into the range function, I changed it to len(iterable) which is the number of items in it

  • You want to append the item in the iterable at the index of i, not just i itself.

def first_4(iterable): 
  result = [] 
  for i in (range(0, len(iterable))): 
    result.append(iterable[i]) 
    if i == 3: break 
  return result

Alternatively, we could have just put 3 as the 2nd item in the range, and it would have stopped on its own, rather than having to break the loop.

And there is also a much much easier way. We can use list slicing like this:

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