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

Srikanth Srinivas
Srikanth Srinivas
1,465 Points

How 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 :)

slices.py
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)
Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Feedback 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.

def first_4(lst):
    return lst[0:4]

def odds(lst):
    return lst[1:(len(lst)):2]

def first_and_last_4(lst):
    def last_4(lst):
        last4 = lst[len(lst)-1:len(lst)-5:-1]
        last4.sort()
        return last4
    return first_4(lst), last_4(lst)

compare the color change in color for lst and list in your code.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

You 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:

Also, the last four items in a list can be obtained using:

last4 = lst[-4:]