How to slice sequences in Python
Learn slicing with its variations and examples.
Slicing of sequences in Python is a crucial and easy to learn concept. In this article we will see different types of slicing and understand them with examples.
Sequence data structures are iterable and the elements of a sequence can be accessed via their index except
Slicing relies on indexing to specify the portion of sequence to extract data from.
As slicing is allowed only for indexable sequences the following data structures are eligible:
- byte sequences
The Slice Notation:¶
my_list[start: end: step]
slice() can be used
my_list[slice(start, end, step)]
step are integers.
start defines the index to start slicing from and continue till index
end - 1(end index is excluded).
There are multiple variations of using slice notation:
[:, end]: Select portion from sequence start till
end - 1
[start: ]: Select portion from start till the end of sequence
[:]: Create a copy of sequence
1. With start and end¶
colors = ["red", "green", "blue", "yellow", "cyan"] print(colors[1: 3])
2. With end only¶
colors = ["red", "green", "blue", "yellow", "cyan"] print(colors[: 4])
['red', 'green', 'blue', 'yellow']
3. With start only¶
colors = ["red", "green", "blue", "yellow", "cyan"] print(colors[2:])
['blue', 'yellow', 'cyan']
step in Slicing¶
step defines the number of index to move forward while slicing an object. If
step is not specified, default value is taken as 1 which means move without skipping any index.
colors = ["red", "green", "blue", "yellow", "cyan"] print(colors[: 4: 2])
With a string:
alphabets = "abcdefghijklmnopqrstuvwxyz" print(alphabets[::2])
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link** This is an affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏