What is Slices in python
#What is slices #python #Python
Slices in Python allow you to extract a subset of elements from sequences like lists, tuples, and strings. They provide an easy and efficient way to manipulate and access data.
Slices are objects that can be stored in variables and used to extract parts of sequences. We use integers to specify the upper and lower bounds of a slice or utilize a slice object.
s = slice(3,6)
lst = [1, 3, 'a', 'b', 5, 11, 16]
text = 'DataScience'
tpl = (1,2,3,4,5,6,7)
print(lst[s]) # Output: ['b', 5, 11]
print(text[s]) # Output: 'aSc'
print(tpl[s]) # Output: (4, 5, 6)
Python allows negative indices, which count from the end of the sequence.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice from -5 to -2 (from the end)
print(numbers[-5:-2]) # Output: [5, 6, 7]
# Reverse the list using negative step
print(numbers[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
A step value determines the interval between elements in the slice.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice with step
sliced_numbers_step = numbers[1:8:2]
print(sliced_numbers_step) # Output: [1, 3, 5, 7]
# Slice with negative step (reversing)
reversed_numbers = numbers[::-1]
print(reversed_numbers) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
sequence[start:stop:step]
.start
defaults to 0
.stop
defaults to the length of the sequence.step
defaults to 1
.Slicing in Python is a powerful tool for data manipulation, making code more concise and readable.