Python slice()
Function
The slice() function in Python creates a slice object that can be used to extract parts of a sequence like a list, tuple, or string. This is very useful when you want to get a sub-part of a sequence using custom start, stop, and step values.
Syntax
slice(stop)
slice(start, stop[, step])
Parameters:
start
– (Optional) The starting index of the slice. Default is 0.stop
– The ending index (exclusive).step
– (Optional) The step size or interval. Default is 1.
Returns:
- A
slice
object that can be used to extract portions from a sequence.
Example 1: Basic Usage with a List
numbers = [10, 20, 30, 40, 50, 60]
s = slice(1, 4)
print(numbers[s])
[20, 30, 40]
Example 2: Using Step with slice()
letters = ['a', 'b', 'c', 'd', 'e', 'f']
s = slice(1, 6, 2)
print(letters[s])
['b', 'd', 'f']
Example 3: slice() with Strings
text = "HelloWorld"
s = slice(0, 5)
print(text[s])
Hello
How is slice() Different from [start:stop:step]?
Python allows slicing using both slice()
and the shorthand notation [start:stop:step]
. They do the same thing but slice()
is more flexible when you want to pass slicing as a parameter to functions or reuse slicing logic.
Use Case: Reusable Slice Logic
def get_middle_part(seq):
s = slice(1, -1)
return seq[s]
print(get_middle_part("Python"))
print(get_middle_part([10, 20, 30, 40]))
ytho
[20, 30]
Common Mistakes
- Forgetting that the
stop
index is exclusive. - Passing strings instead of integers to
slice()
. - Assuming
slice()
extracts the values itself — it only creates a slice object.
Interview Tip
Use slice()
when writing reusable logic or custom sequence functions. Knowing how to slice efficiently is helpful in coding rounds involving arrays or strings.
Summary
slice()
returns a slice object for use with sequences.- You can specify
start
,stop
, andstep
. - Works with lists, tuples, strings, and other slicable types.
Practice Problem
Write a function that takes a list and returns every third element starting from index 0 using slice()
.
def every_third_element(lst):
s = slice(0, len(lst), 3)
return lst[s]
print(every_third_element([1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 7]