Container Data Structures

Slicing in Lists and Tuples

The slicing operator can be applied to the lists and tuples as it can to the strings:

temp = [1, 3, 5, 6, 7]

print(temp[2:5])

will output [5, 6, 7] .

You can read more about slicing in the Strings in Detail section.

It is possible to refer to list and tuple items using negative indexing with length of the container. Whenever a negative index (-x, where x is a positive integer) is used, it is going to refer to the item at position len(container)-x, i.e. container[-1]is equal to container[len(container)-1]. For a list or tuple containing 10 items, the item at container[-3] is the same item at container[7].

Negative indexing can also be applied to the slicing operator.

Items in a list can be modified either one at a time or by using the slicing operator (tuples are immutable, they cannot be modified):

temp = [1, 3, 5, 6, 7]
print(temp)

temp[1] = 13

temp[2:4] = [15, 16]

print(temp)

Output:

[1, 3, 5, 6, 7]
[1, 13, 15, 16, 7]

Replacing the items with the slicing operator has some additional effects:

temp = [1, 3, 5, 6, 7]

temp[2:4] = [15, 16, 17]

print(temp)

Output:

[1, 3, 15, 16, 17, 7]

What happened in this example is that we wanted to insert a list of three items into a slice of length two. The existing elements corresponding to the slice are replaced with the new values and the remaining items in the additional list are inserted after the previous items, shifting the elements in the original list towards the end of that list.