Skip to content

Python List Slicing Explained: start, stop, step and Examples

Python slicing extracts a portion of a sequence using sequence[start:stop:step]. The stop position is excluded, and the step must not be zero. This tutorial explains forward and reverse slices with practical examples.

Syntax

sequence[start:stop:step]

start – Starting integer where the slicing of the object starts. Default to None if not provided.

 stop — Exclusive bound. For a positive step, the last included position is before stop; with negative steps, indices decrease and the stop bound is still excluded.

step — Optional integer stride between selected positions. Omitting it uses a stride of 1; a negative stride traverses backward, and zero raises ValueError.

  • for zero or positive value of start/end, elements are counted from the start of the iterable.
  • for negative value of start/end, elements are counted from the end of the iterable (for e.g.-1 is the last element, -2nd to last etc).
  • If step is 0, Python raises ValueError: slice step cannot be zero.
  • If step value is negative, then the elements are selected in reverse order.

Use a colon to separate slice boundaries; for example, items[:] copies a list and items[::-1] reverses it. Omitted bounds are interpreted according to the direction of the step.

Default value of start and end

  • When start value is not provided – Default value of start depends on step size. When step value is positive or omitted, it defaults to the start of the iterable and if step value is negative, start defaults to the end of the iterable.
  • When end value is not provided – Similar to start, default value of end depends on step size. When step value is positive or omitted, it defaults to the end of the iterable and if step value is negative it defaults to the start of the iterable.

Let’s create a list to show slicing and Slice at position 3 to 6.

#Creating a list
num_lst = [10,20,30,40,50,60,70,80,90,100]

#Start the slice object at position 3, and slice to position 5, and return the result:
x = num_lst[slice(3, 6)]
print(x)

#Output>>>
# [40, 50, 60]

Basic usage of slicing

Python supports slice notation for sequences such as lists, strings, tuples and ranges, but not for arbitrary iterables such as generators or sets. Slicing creates a new sequence from an existing sequence (for lists, the new list is a shallow copy). It takes start, end and step as an argument. Each of them has a default value as described above. Because of its ease and simplicity it is also popular in data science libraries like NumPy and Pandas.

#Creating a list
num_lst = [10,20,30,40,50,60,70,80,90,100]

#If start is not provided but end and step value are provided
print(num_lst[:5:2])

#Output
# [10, 30, 50]

#If start and end values are not provided but steps value is provided
print(num_lst[::2])

#Output
# [10, 30, 50, 70, 90]

#If start and steps are not provided but end value is provided
print(num_lst[:5])

#Output>>>
# [10, 20, 30, 40, 50]

#If end is not provided but start and steps values are provided
print(num_lst[3::2])

#Output>>>
# [40, 60, 80, 100]

#If end and steps are not provided but start value is provided
print(num_lst[3::])

#Output>>>
# [40, 50, 60, 70, 80, 90, 100]

When given values are out of range

#If a position that exceeds the number of elements
print(num_lst[2:20])   #It will not give error, but take the end of the iterable

#Output>>
# [30, 40, 50, 60, 70, 80, 90, 100]

If output returns, no elements

If a list slice selects no elements, it returns an empty list. Slicing a string instead returns an empty string.

print(num_lst[10:20])   #It will not give error

#Output>>>
# []

print(num_lst[2:2])   #It will not give error

#Output>>>
# []

print(num_lst[5:2])

#Output>>>
# []

Using negative indexing

Use negative index to refer element position with respect to end of the list. For e.g. -1 index refers to the last element of the list.

#If end value is negative
print(num_lst[4:-1])

#Output>>>
# [50, 60, 70, 80, 90]

Here -1 refers to the last element and as the end element is not include, so it selects the elements till the second last element.

#If start is negative
print(num_lst[-3:]) # This selects the last three elements

#Output>>>
# [80, 90, 100]

#If start, end and steps are negative
print(num_lst[-2:-7:-3])

#Output>>>
# [90, 60]

#If start and steps are negative
print(num_lst[-2::-3])

#Output>>>
# [90, 60, 30]

Getting a list in reverse order

If step value is negative then the elements will selected in reverse order.

#If start and end value are not provided then it will return all element in reversed order
print(num_lst[::-1])

#Output>>>
# [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

#If Step value is negative
print(num_lst[5:2:-1])

#Output>>>
# [60, 50, 40]

#If start value is after the steps, it will return an empty list
print(num_lst[2:5:-1])

#Output
# []

Get substring using slice object

A slice object can index a sequence such as a string, list, tuple or range. Sets do not support positional slicing. This is used for extended slicing. If only one value is passed then start and step value is considered as none i.e. start will default to starting of the iterable and step will default to 1.

# Getting a substring from the given string 

string_var = 'PickupBrain'

# If stop = 6
slice_object = slice(6) 
print(string_var[slice_object])  

#Output>>>
# Pickup

# start = 2, stop = 7, step = 2
slice_object = slice(2, 7, 2)
print(string_var[slice_object])

#Output>>>
# cuB

Substitute part of a list

Slicing notation can also be used to assign elements.

#Creating a list
num_lst = [10,20,30,40,50,60,70,80,90,100]
num_lst[:5] = [1,2,3,4,5]
print(num_lst)

#Output>>>
# [1, 2, 3, 4, 5, 60, 70, 80, 90, 100]

Replace and Resize part of the list

In this case we extend the original list.

num_lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# Replacing first four element of list with bigger list
num_lst[:4] = [1,2,3,4,5,6,7]
print(num_lst)

#Output>>>
# [1, 2, 3, 4, 5, 6, 7, 50, 60, 70, 80, 90, 100]

It’s also possible to replace bigger sub-list with a smaller sub-list:

num_lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
num_lst[:4] = [7]
print(num_lst)

#Output>>>
# [7, 50, 60, 70, 80, 90, 100]

Replace Every n-th Element

Following code will replace every 2nd element with a ‘*’:

num_lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
num_lst[::2] = ['*', '*', '*', '*', '*']
print(num_lst)

#Output>>>
# ['*', 20, '*', 40, '*', 60, '*', 80, '*', 100]

For extended slice assignment with a stride other than 1, the replacement iterable must have exactly as many items as the selected positions. Otherwise Python raises ValueError. With a stride of 1, a replacement can grow or shrink the list.

num_lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
num_lst[::2] = [1, 2,3,4]
print(num_lst)

#Output>>>
# ValueError: attempt to assign sequence of size 4 to extended slice of size 5

We can use negative step too

num_lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
num_lst[::-2] = [1,2,3,4,5]
print(num_lst)

#Output>>>
# [10, 5, 30, 4, 50, 3, 70, 2, 90, 1]

By providing start and stop values 

num_lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
num_lst[1:5:2] = [4, 6]
print(num_lst)

#Output>>>
# [10, 4, 30, 6, 50, 60, 70, 80, 90, 100]

Tip: For large lists, slicing allocates a new list. For lazy iteration over a sequence or generator, consider itertools.islice(); it does not accept a negative step.

Examples: forward and reverse list slicing

Given values = [10, 20, 30, 40, 50], values[1:4] returns [20, 30, 40]; values[::2] returns [10, 30, 50]; and values[::-1] returns a reversed copy. The end index is exclusive. With a negative step, omitted boundaries follow the reverse traversal direction. A slice of a list produces a new list, but it is a shallow copy: nested mutable objects are still shared.

Common slicing mistakes

Do not treat stop as inclusive. Avoid [::0], which raises ValueError. Slice syntax works on sequences, not on every iterable; convert a generator to a list or use itertools.islice where appropriate. slice(start, stop, step) creates a reusable slice object, for example every_other = slice(None, None, 2) and values[every_other].

Validated slice examples and practical limits

For num_lst = [10, 20, 30, 40, 50, 60], num_lst[1:4] is [20, 30, 40], num_lst[::-1] reverses the list, and num_lst[slice(3, 6)] is [40, 50, 60]. A slice does not raise IndexError just because a bound exceeds the sequence length. However, a zero step raises ValueError, and assigning to an extended list slice with a non-unit step requires matching lengths.

For more on indexing, see finding an item with list.index() and iterables versus iterators.

Leave a Reply

Your email address will not be published. Required fields are marked *