Understanding slicing in Python


Slicing in Python refers to the technique of selecting a range of elements from a sequence, such as a string, list, or tuple. Slicing is achieved by specifying a range of indices, separated by a colon, within square brackets following the sequence.


Here’s the syntax for slicing:

sequence[start:stop:step]
  • start: The index where the slice starts (inclusive). If start is not specified, it defaults to 0.
  • stop: The index where the slice ends (exclusive). If stop is not specified, it defaults to the end of the sequence.
  • step: The step size between elements in the slice. If step is not specified, it defaults to 1.


Let’s look at some examples:

>>> s = "hello world"
>>> s[0:5]   # select the first 5 characters
'hello'

>>> s[6:]    # select everything after the space
'world'

>>> s[:5]    # select everything up to the first space
'hello'

>>> s[::2]   # select every second character
'hlowrd'

>>> s[::-1]  # reverse the string
'dlrow olleh'


List of all possible Slice methods format:

  1. [start:end] – Returns the slice from ‘start’ index to ‘end-1’ index.
  2. [start:] – Returns the slice from ‘start’ index to the end of the sequence.
  3. [:end] – Returns the slice from the beginning of the sequence to ‘end-1’ index.
  4. [start:end:step] – Returns a slice from ‘start’ to ‘end-1’ index with ‘step’ intervals.
  5. [::-1] – Returns the reverse of the sequence.
  6. [:] – Returns a copy of the entire sequence.
  7. [::] – Returns a copy of the entire sequence.
  8. [start:end:step] – Returns a slice from ‘start’ to ‘end-1’ index with ‘step’ intervals.
  9. [-1] – Returns the last item of the sequence.
  10. [-n:] – Returns the last ‘n’ items of the sequence.
  11. [:-n] – Returns all the items of the sequence except the last ‘n’ items.


All possible sample code:

my_list = [1, 2, 3, 4, 5]

# Get the first element
print(my_list[0])

# Get the last element
print(my_list[-1])

# Get the first three elements
print(my_list[:3])

# Get the last two elements
print(my_list[-2:])

# Get every other element starting from the second
print(my_list[1::2])

# Reverse the list
print(my_list[::-1])

# Get the second through fourth elements
print(my_list[1:4])

# Get every other element starting from the first
print(my_list[::2])

# Get every third element starting from the second to the second last element
print(my_list[1:-1:3])

# Assign new values to elements using slice notation
my_list[:3] = [0, 0, 0]
print(my_list)

# Delete elements using slice notation
del my_list[-2:]
print(my_list)

# Copy the entire list using slice notation
copy_list = my_list[:]
print(copy_list)

Leave a Reply

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