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

Manfredi Martorana
Manfredi Martorana
19,470 Points

Slicing

Hi, I don't understand how to complete Python Slicing Challenge. In particular I don't know how to slice the first 4 and the last 4 elements of a list.

Thanks for the help ;)

Hi Manfredi,

Take a look at the following two examples. I hope this will help you understand slicing better.

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> len(a)
10
>>> a[len(a) - 4:] # a[6:len(a)]
[7, 8, 9, 10]
>>> a[-4:] # Another way!
[7, 8, 9, 10]
>>> a[:4] # a[0:4]
[1, 2, 3, 4]
>>> str[:4]
'hell'
>>> str = 'hello world'
>>> str[:4] # First 4, you can also specify str[0:4]
'hell'
>>> str[-4:]
'orld'

Eugene

3 Answers

Manfredi Martorana
Manfredi Martorana
19,470 Points

Well, I don't know how to write a function that accept a list, and return the first and last four elements.

Thank you

Manfredi

I have not worked on that challenge, but I think this is what you are asking:

>>> def sublist(lst):
...   return # add your slicing code here
... 
>>> sublist(str)
('hell', 'orld')
>>> sublist(a)
([1, 2, 3, 4], [7, 8, 9, 10])

Eugene

Manfredi Martorana
Manfredi Martorana
19,470 Points

Perfect... One last thing: the output must be in the same bracket!

Manfredi

Try to work on the answer. You are almost there with these hints. Good luck!