Python Lessons – 5.5 Slicing Lists

Python Lessons - 5.5 Slicing lists

List Slicing

You’ve just seen how to get a single item from a list by writing the list name and the element index

listname[2]

Slicing is a more advanced way of getting more items at once from a list. In fact, if we want to obtain the elements between two indexes of a list we can express the two extreme indices separated by two points:. The value corresponding to the maximum index will not be included. The returned value will be a list in turn (a sublist).

listname[indexmin:indexmax]

Let’s take an example:

if you run it you get

If you omit the lower index we will get all the elements of the list included between the first element and the defined index. Basically it is as if the first index was 0.

if you run it, you get

Same thing…, if the upper index is omitted, we will get all the elements of the list starting from the indicated index up to the last element.

if you run it, you get

Moreover slicing also foresees a possible third number. This number represents the step, ie how many elements must be excluded every element to be taken in the range indicated by the first two indices.

if you run it, you get:

Finally slicing also includes the use of indices with negative values. These indices (as we have seen) start from the final element.

if you run it, you get:

If the negative value is instead used for the third number (leaving the other two empty), this will return the inverted list in the order. If -1 we have the inversion of the list, if the list is always less inverted but only the alternating elements (as step).

if you run it, you get:

⇐ Go to Python Lesson 5.4 – Tuples

Go to Python Lesson 5.6 – List comprehension ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.