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 trialSrikanth Srinivas
1,465 PointsHow do I make the brackets go away?
So my function works.. Sort of..
It will print the first and last 4 items in a list, but makes it appear as two separate lists within a larger list. How do I get it to appear as just one large list? Thanks in advance :)
def first_4(list):
return list[0:4]
def odds(list):
return list[1:(len(list)):2]
def first_and_last_4(list):
def last_4(list):
last4 = list[len(list)-1:len(list)-5:-1]
last4.sort()
return last4
return first_4(list), last_4(list)
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsYou are looking to flatten two lists into a single list. There are many solutions. With differing complexity and readability. Replace the return
in first_and_last_4()
statement with a list comprehension:
return [item for sublist in [first_4(lst), last_4(lst)] for item in sublist]
Other resources:
- Flattening a shallow list in Python
- Comprehension for flattening a sequence of sequences?
- Making a flat list out of list of lists in Python
Also, the last four items in a list can be obtained using:
last4 = lst[-4:]
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsFeedback on readability. Using the name of a built-in function as a function argument and an variable name makes it hard to read. In general it's bad practice to do so. Here's your code with new names. Also increased indent and spacings.
compare the color change in color for
lst
andlist
in your code.