How to slice in python

The slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).

Example

text = 'Python Programing'

# get slice object to slice Python sliced_text = slice(6)

print(text[sliced_text]) # Output: Python


slice() Syntax

The syntax of slice() is:

slice(start, stop, step)

slice() Parameters

slice() can take three parameters:

  • start (optional) - Starting integer where the slicing of the object starts. Default to None if not provided.
  • stop - Integer until which the slicing takes place. The slicing stops at index stop -1 (last element).
  • step (optional) - Integer value which determines the increment between each index for slicing. Defaults to None if not provided.

slice() Return Value

slice() returns a slice object.

Note: We can use slice with any object which supports sequence protocol (implements __getitem__() and __len()__ method).


Example 1: Create a slice object for slicing

# contains indices (0, 1, 2)
result1 = slice(3)
print(result1)

# contains indices (1, 3)

result2 = slice(1, 5, 2)

print(slice(1, 5, 2))

Output

slice(None, 3, None)
slice(1, 5, 2)

Here, result1 and result2 are slice objects.

Now we know about slice objects, let's see how we can get substring, sub-list, sub-tuple, etc. from slice objects.


Example 2: Get substring using slice object

# Program to get a substring from the given string 

py_string = 'Python'

# stop = 3
# contains 0, 1 and 2 indices

slice_object = slice(3)

print(py_string[slice_object]) # Pyt # start = 1, stop = 6, step = 2 # contains 1, 3 and 5 indices slice_object = slice(1, 6, 2) print(py_string[slice_object]) # yhn

Output

Pyt
yhn

Example 3: Get substring using negative index

py_string = 'Python'

# start = -1, stop = -4, step = -1
# contains indices -1, -2 and -3

slice_object = slice(-1, -4, -1)

print(py_string[slice_object]) # noh

Output

noh

Example 4: Get sublist and sub-tuple

py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')

# contains indices 0, 1 and 2

slice_object = slice(3)

print(py_list[slice_object]) # ['P', 'y', 't'] # contains indices 1 and 3

slice_object = slice(1, 5, 2)

print(py_tuple[slice_object]) # ('y', 'h')

Output

['P', 'y', 't']
('y', 'h')

Example 5: Get sublist and sub-tuple using negative index

py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')

# contains indices -1, -2 and -3

slice_object = slice(-1, -4, -1)

print(py_list[slice_object]) # ['n', 'o', 'h'] # contains indices -1 and -3

slice_object = slice(-1, -5, -2)

print(py_tuple[slice_object]) # ('n', 'h')

Output

['n', 'o', 'h']
('n', 'h')

Example 6: Using Indexing Syntax for Slicing

The slice object can be substituted with the indexing syntax in Python.

You can alternately use the following syntax for slicing:

obj[start:stop:step]

For example,

py_string = 'Python'

# contains indices 0, 1 and 2

print(py_string[0:3]) # Pyt

# contains indices 1 and 3

print(py_string[1:5:2]) # yh

Output

Pyt
yh

❮ Built-in Functions


Example

Create a tuple and a slice object. Use the slice object to get only the two first items of the tuple:

a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
print(a[x])

Try it Yourself »


Definition and Usage

The slice() function returns a slice object.

A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.


Syntax

Parameter Values

ParameterDescription
start Optional. An integer number specifying at which position to start the slicing. Default is 0
end An integer number specifying at which position to end the slicing
step Optional. An integer number specifying the step of the slicing. Default is 1

More Examples

Example

Create a tuple and a slice object. Start the slice object at position 3, and slice to position 5, and return the result:

a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(3, 5)
print(a[x])

Try it Yourself »

Example

Create a tuple and a slice object. Use the step parameter to return every third item:

a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(0, 8, 3)
print(a[x])

Try it Yourself »


❮ Built-in Functions


How do you slice in Python?

slice() can take three parameters:.
start (optional) - Starting integer where the slicing of the object starts. Default to None if not provided..
stop - Integer until which the slicing takes place. ... .
step (optional) - Integer value which determines the increment between each index for slicing..

How do I slice a data list in Python?

The format for list slicing is [start:stop:step]. start is the index of the list where slicing starts. stop is the index of the list where slicing ends. step allows you to select nth item within the range start to stop.

What is slice operation in Python example?

Python slice() Function The first function takes a single argument while the second function takes three arguments and returns a slice object. This slice object can be used to get a subsection of the collection. For example, if we want to get first two elements from the ten element? s list, here slice can be used.

What is :: In slicing?

Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:) With this operator, one can specify where to start the slicing, where to end, and specify the step.