Site icon Meccanismo Complesso

Python Lessons – 5.5 Slicing Lists

Python Lessons - 5.5 Slicing lists m
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:

list = [ 9,8,7,6,5,4,3,2,1]
print(list[2:5])

if you run it you get

>>>
[7, 6, 5]

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.

list = [ 9,8,7,6,5,4,3,2,1]
print(list[0:5])
print(list[:5])

if you run it, you get

>>>
[9, 8, 7, 6, 5]
[9, 8, 7, 6, 5]

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.

list = [ 9,8,7,6,5,4,3,2,1]
print(list[5:])

if you run it, you get

>>>
[4, 3, 2, 1]

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.

list = [ 9,8,7,6,5,4,3,2,1]
print(list[1:6:2])

if you run it, you get:

>>>
[8, 6, 4]

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

list = [ 9,8,7,6,5,4,3,2,1]
print(list[2:-2])

if you run it, you get:

>>>
[7, 6, 5, 4, 3]

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).

list = [ 9,8,7,6,5,4,3,2,1]
print(list[::-1])
print(list[::-2])

if you run it, you get:

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]

⇐ Go to Python Lesson 5.4 – Tuples

Go to Python Lesson 5.6 – List comprehension ⇒

Exit mobile version