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

how do I get first and last 4 elements using slicing from a list ?

return (1:4,:-4)

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

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

def first_and_last_4(inlist) :
    return inlist[1:4,:-4]

1 Answer

Stephen Bone
Stephen Bone
12,359 Points

Hi Ankush

In the first function first_4 you already get the first four letters so you could just copy the index again or even call that function.

Then to get the last four you want to start four from the end of the string and continue until the end. The way we start counting from the end of the string is to put a - (hyphen) in front of the starting index. So in this case your start value is -4.

And I think I'm right in saying for your return value you will have to slice the first four then concatenate the last four as in inlist[] + inlist[]. I don't think it would understand trying to do both of them in one slice as you have it above although I could be wrong.

Hopefully this will get you on the right track but if you need any further help just let me know.

Hope it helps!

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Nope, there's no way to do multiple slices in one call ([x:y,a:b]). You have to add the two slices together.