Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How slicing in Python works

Solution:

The process of getting a sub-sequence of a sequence by giving a starting and ending index is known as slicing. The colon: operator is used in Python to perform slicing.

Here’s the syntax:


sequence[start_index:end_index]

Where start_index is the index of the sub-sequence's first element and end_index is the index of the sub-sequence's last element (excluding the element at end_index). To slice a sequence, use square brackets [] separated by a comma with the start and end indices.

Here’s an example -


my_list = ['apple', 'banana','cherry','date']
print(my_list[1:3]) #output: ['banana','cherry']

Here, we used slicing in the preceding code to access a sub-sequence of my_list comprising the second and third entries.

In a slice, you can also omit the start_index or the end_index to get all the components from the beginning or end of the sequence. 

Here’s an example -


my_list = ['apple', 'banana','cherry','date']
print(my_list[:2]) #output: ['apple','banana']
print(my_list[2:]) #output: ['chery', 'date']

For more details, visit our Python blogs.