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 Introduction To Slices

Frances Tang
Frances Tang
24,767 Points

Slice video 1:49

Hello fellow coders,

I got very confused over the process below:

my_list = list(range(1, 6)) my_list [1, 2, 3, 4, 5] my_list[1: 3]

[2, 3]

So, since the index number is 1 and 3, shouldn't we get [2, 4] instead of [2, 3] from my_list?

And also, why is list(range(1, 6)) is [1, 2, 3, 4, 5], not [1, 2, 3, 4, 5, 6]?

Thank you for your time in advance!

2 Answers

Sam Dale
Sam Dale
6,136 Points

So for list(range(1, 6)) the reason it gives you [1, 2, 3, 4, 5] is because range has the following syntax: range(start, upper_bound). This means that the range will go from the start up until the upper_bound but not including the upper bound. The reason Python does this is that it is very convenient to use len() to write something like:

blah = [1, 2, 3, 4]
for i in range(0, len(blah)):
    print(blah[i])

Now the same principle is at play with the substring. For my_list = [1, 2, 3, 4, 5], and my_list[1:3], goes from the start up until the upper bound, but not including the upper bound. <br>Another way to think about this is if I showed you: 1 <= x < 6. x could be 1, 2, 3, 4, or 5, but x cannot be 6, because it goes up to but doesn't include 6. Hope that helps a little!

Amy-Kate Andrews
Amy-Kate Andrews
26,286 Points

I agree with Sam Dale (above).

So in the example, list(range(1,6)), when creating a list, 1 is the first number to start the iteration, and 6 is the number that the list will go up to but will not include.

Then when you select from the list, using my_list[1:3], 1 is the starting index (which is zero based), and 3 is the index that the slice will go up to but will not include.