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 Deleting Or Replacing Slices

Hiren Mistry
Hiren Mistry
1,138 Points

Confused on the mechanics of slicing

I don't quite understand when you have: my_list = ('a', 'b', 'c' 'd', 5, 6, 7, 'f') my_list[4:7] and you get 5, 6, 7 I don't get why you call for 4 elements and only recieve 3, why isn't 'f' not listed as well?

I understand Python counts from 0.

If I were to do the same thing in R my_list = c('a', 'b', 'c', 'd', 5, 6, 7, 'f') mylist[4:7] I would get 'd',5,6,7

Besides that R starts at 1, I asked for 4 things and it gave me 4 things.

Why does Python not do the same? What is the purpose behind it?

1 Answer

Gavin Ralston
Gavin Ralston
28,770 Points

In Python, the ending position in a range or a list isn't inclusive.

This language is not alone in doing that, but it does vary from language to language.

So what you're literally asking in Python is "Give me items from element 4 up to, but not including 7" -- or three elements.