Advanced Topics in Python: Practice Makes Perfect


#1

I'm just hoping someone can explain to me why my code produces what it does. The question is easy: create an inclusive list of the middle third elements in to_21 = range(1,22). I first tried:

to_21 = range(1, 22)

middle_third = to_21[8:15:1]

But I get this error:

In the list slicing syntax lesson, it says:

But in this example, the starting point is excluded and the ending point is included. Can someone explain when the start point is inclusive/end point exclusive and vice versa? Thanks!


#2

Hi kcmileiq!

I think the confusion comes from what the range() function is doing, versus what the slicing is doing.

(We can disregard the stride for now; it defaults to 1 if not named).

To make it simpler, let's do:

my_numbers = range(1, 5)
print my_numbers

We'll get a result of [1, 2, 3, 4] for my_numbers. Of course 5 is left out because the range includes the first number, but it excludes the last number.

Slicing works the same way (includes first, excludes last) but the important point is that it refers to indexes, not the numbers themselves.

So below:

my_numbers = range(1, 5)
x = my_numbers[1:3]
print x

Print x doesn't print [1, 2], but rather [2, 3], because 2 is actually at index number 1 and 3 is at index number 2 (remember indexes start at 0).

It's less confusing if we use letters:

letters = ["a", "b", "c", "d"]
mid = letters[1:3]
print mid

Print mid gives us ["b","c"], because "a" is at index 0, "b" is at index 1, "c" is at index 2, and "d" is at index 3.

I hope that makes sense! :smile:


#3

This makes perfect sense. Thank you so much for such a clear explanation!


#4

hey here is my code which is perfectly working
to_21 = range(1 , 22)
odds = to_21[0:21:2]
middle_third = to_21[7:14:1]


#5

this worked for me.
to_21 = range(1,22)
odds = to_21 [ : : 2]
middle_third = to_21 [7:14]