To slice a list in Python, you can use list slicing notation.
In this example,
numbers
with integer values.numbers[start:end]
to create a new list from index 1 to index 4 (exclusive).numbers = [1, 2, 3, 4, 5]
sliced_numbers = numbers[1:4]
print('Sliced list:', sliced_numbers)
Sliced list: [2, 3, 4]
In this example,
words
with string values.words[start:end]
to create a new list from index 2 to index 5 (exclusive).words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
sliced_words = words[2:5]
print('Sliced list:', sliced_words)
Sliced list: ['cherry', 'date', 'elderberry']
In this tutorial, we learned How to Slice a List in Python language with well detailed examples.