Python Code Challenges: Lists (Advanced) Q2

Ok, so I am definitely reading this question wrong. Well, that and I cant completely remember how all the sytnax relates to one another, so here goes:

I still don’t fully understand slicing and am not sure how the the middle indexes are being removed using “start and end”. I don’t see where, or how those parameters are correlated to the list?

Slicing is quite straight forward and easy to learn, especially if you are fully briefed on how indices work and are written.


The index can be positive or negative, depending the end of the list you want to count from.

0..N      =>  left to right
-1..-N    =>  right to left

Focusing on the positive indices including zero, we use the same subscript syntax but for the special operator, : which acts as the index separator allowing for two indices.


The end is excluded from the slice. As an interval we could write it,

 (start, end]

Consider the list, a = [1, 2, 3, 4, 5, 6, 7, 8, 9].

The first element can be sliced with,

a[:1]    =>  [1]

Note that it is still a list object. A slice is a list.

The first four elements,

a[:4]    =>  [1, 2, 3, 4]

The value at index 4 is excluded, as we can see. Notice in both examples we did not specify the start. It defaults to 0 when omitted. The all important operator is there to trigger the slicing engine.

Slices are virtual and will never raise an exception if given invalid indices. Python will do what it can and that’s what you’ll get.

a[10:]    =>  []

Above we set the start index out of range, but the interpreter doesn’t care. It just gives back an empty list.

Similar to the above configuration, we can pull out the last four elements,

a[5:]    =>  [6, 7, 8, 9]

Notice we omitted the end index, this time. The slice starts at index 5 and includes the remainder of the list.

Up to now we’ve looked at start and end indices, but there is a third parameter, the step or stride.

a[::2]    =>  [1, 3, 5, 7, 9]
 even indices

a[1::2]    =>  [2, 4, 6, 8]
   odd indices

Negative indices work, as well…

a[-4:]    =>  [6, 7, 8, 9]

Sometimes they are easier and more intuitive, and do not require calculation.

For finding the middle element(s), we have simple formulae derived from the length of the list:

# odd length
n = len(a)
m = a[int(n/2):int(-n/2)]
print (m)    =>  [5]

# even length
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
n = len(b)
m = b[int(n/2)-1:int(-n/2)+1]
print (m)    =>  [5, 6]


# odd length
n = int(len(a) / 2)
m = a[n:-n]
print (m)    =>  [5]

# even length
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
n = int(len(b) / 2)
m = b[n - 1:-n + 1]
print (m)    =>  [5, 6]

Thank you so much mtf! that was extremely helpful! Admittedly, getting used to calculating the middle elements will be tricky. I’ll have to be sure to practice that!