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 trialSergei Miroshnikov
3,313 PointsBummer! 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
Front End Web Development Techdegree Graduate 84,738 PointsI 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]
Sergei Miroshnikov
3,313 Pointsyes, thank you very much :) !
Sergei Miroshnikov
3,313 PointsSergei Miroshnikov
3,313 PointsI am sorry , but from the question is not clear at all that an iterable is a list ! Thank you , if it is a list and not a variable I will try your solution
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsDoes it make sense now though?
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsDoes it make sense now though?
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsI guess technically a list is an iterable, but not necessarily the other way around. I don't want to wade too much into that territory since I'm not that much of a python guru, but I wanted to point that out.