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

Ben Swift
Ben Swift
6,201 Points

Confused with first_and_last_4

Make a function name first_and_last_4 that accepts an iterable and returns the first 4 and last 4 items in the iterable.

slices.py
def first_4(iterable):
  return iterable[0:4]

def odds(iterable2):
  return iterable2[1::2]

def first_and_last_4(iterable4):
  return iterable4[0:4] + iterable[:-4]

4 Answers

You made a mistake on your first_and_last_4(). First of all, you called non global variable iterable, so python thinks it is not defined. Second mistake is your sliced it like this '[:-4]'. Python interprets this as [Begin from index 0: End at the 4'th index from last].

you can use the below code:

To get the last 4 item, i looked for the length and minus 4.

def first_and_last_4(iterable4):
  '''(str) -> str
  returns the item from the first 4 and last 4 index.
  '''
  return iterable4[:4] + iterable4[len(iterable4)-4:]
Ben Swift
Ben Swift
6,201 Points

Thank you so much!

Milos Town
seal-mask
.a{fill-rule:evenodd;}techdegree
Milos Town
Python Web Development Techdegree Student 2,633 Points

Ben, You were almost there! Make sure you use the same parameter.

def first_and_last_4(iterable4):
  return iterable4[0:4] + iterable4[-4:]

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

def first_and_last_4(n): return n[:4] + n[-4:]

def odds(index): return index[1::2]

def reverse_evens(index): return index[::22][::-1]

just try this

Amanda Perez
PLUS
Amanda Perez
Courses Plus Student 2,056 Points

I have tried all answers including my own and all I get is couldn't find 'first_4' :(

def first_4(itera): return itera[:4] def first_and_last_4(n): return n[:4] + n[-4:] def odds(index): return index[1::2] def reverse_evens(index): return index[::22][::-1]