What are the different ways one can slice a sequence in Python?

  • Are there any other ways to slice sequences in Python other than specifying the range?
  • Is there a way obe can store the required slicing in a variable and call it on different types of sequences later?

Slicing is used to get a sequence of elements from a sequence data type in Python. Sequence data types in Python include lists, tuples, strings, ranges etc.


The following are the ways one can slice sequences in Python:


1. Specifying the range of indexes.

sequence[start:stop:step]

Here, the a slice of sequence from start to stop with step is returned in the same data type as that of sequence. It is to be noted that stop element is excluded from the slice.

If step is omitted then it defaults to one.
If start is omitted, then the elements from 0.
if stop is omitted, the the elements continue till last element of the sequence.

Examples are as follows:

>>> string = 'sequence'

# the following will return a string with elements starting from index 2 
# and going up till element at index 7 ( 7 excluded) with step size as 2.
>>> string[2:7:2]
'qec'

>>> my_list = [1, 2, 3, 4, 5, 6]
>>> my_list[2:]
[3, 4, 5, 6]

>>> my_tuple = (1, 2, 3, 4, 5, 6)
>>> my_tuple[:4]
(1, 2, 3, 4)

# the following will return the list from 2nd last element to the end of the list
>>> my_list = [1, 2, 3, 4, 5, 6]
>>> my_list[-2:]
[5, 6]

>>> my_tuple = (1, 2, 3, 4, 5, 6)
>>> my_tuple[-4:-1]
(3, 4, 5)



2. Slicing using slice() function

A sequence of object of any type can be sliced using slice() . Here, slicing of a certain type can be stored in a variable and be called later in the code.

The syntax is as follows:

slice(stop)
slice(start, stop, step)

Here, this function returns a slice object representing the set of indices specified by slice(start, stop, step). The start and step arguments default to None.

Let us look at a certain examples:

>>> my_list = [1, 2, 3, 4, 5, 6]
>>> slice1 = slice(3)
>>> print(my_list[slice1])
[1, 2, 3]


>>> slice2 = slice(1, 5, 2)
>>> print(my_list[slice2])
[2, 4]

Negative indexing can also be used in slice().



3. Slicing using itertools.islice()

As we are using the itertools.islice() makes an iterator that returns selected elements from the iterable.

The syntax is as follows:

itertools.islice(iterable,stop)
itertools.islice(iterable, start, stop[, step])

If the start is None, then iteration starts at zero.
If the step is None, then the step defaults to one.
If the stop is None, then iteration continues until the iterator is exhausted, otherwise, it stops at the specified position.
islice() doesn’t support negative values for start, stop, and step.

Have a look at the following example:

>>> import itertools
>>> my_tuple = (1, 2, 3, 4, 5, 6)
>>> nums = itertools.islice(my_tuple, 2, 6, 2)
>>> print(tuple(nums))
(3, 5)