Slicing of Tuple in Python: Methods, Examples & Interview Questions

Slicing of a tuple means extracting a part (or slice) of the tuple. In Python, tuple slicing can be done in two primary ways:

  1. Using the colon (:) operator
  2. Using the slice() method

In previous articles, we learned about Access Tuple Elements by Index in Python, How to Change Elements in a Tuple in Python and How to Remove Elements from a Tuple in Python. In this article, we will learn about Slicing of Tuple in Python. We will explore different methods, example programs and interview questions related to slicing of tuple in Python.

Slicing of Tuple in Python

Slicing of tuple in Python is very similar to slicing of list. In this article we will use the index positions of tuple elements to perform the slicing of tuples.

Methods for Slicing of Tuple in Python

There are two methods for slicing of tuple in Python. Syntax is similar for both the methods.

Slicing using the colon (:) operator with index positions => tuple[start:end:step]

Slicing using the slice() method along with index positions => tuple[slice(start, end, step)]

  • start (optional) – This is an optional parameter. The index position from where slicing begins. If not provided, then slicing starts from the first element (index 0). start index position can be defined using positive indexing or on negative indexing.
  • end – This is a mandatory parameter with slice() method but is optional with colon (:) operator. This is the index position at which slicing ends. Elements up to index end-1 are included in the sliced tuple. If end index is not given then search will happen till the last element in the tuple. end index position can be defined using positive indexing or on negative indexing.
  • step (optional) – This is an optional parameter. It defines the interval between the indices. It means, the jump in index position to get the next element. The default step is 1.
  • Return value – Both slicing methods will return a new sliced tuple without modifying the original tuple. Even if we don’t have any element in sliced tuple this will not raise any error.
# slicing range will be from index 1 to 8 (end - 1) and step of 2
print("slicing range will be from index 1 to 8 (end - 1) and step of 2")

shbytes_tuple=(0,1,2,3,4,5,6,7,8,9,10,11)
print(shbytes_tuple, type(shbytes_tuple))

print(shbytes_tuple[1:9:2])     # colon operator, start index 1, end index 9, step by 2
print(shbytes_tuple[slice(1, 9, 2)])  # slice method, start index 1, end index 9, step by 2

# Output
# slicing range will be from index 1 to 8 (end - 1) and step of 2
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) <class 'tuple'>
# (1, 3, 5, 7)
# (1, 3, 5, 7)

No Error Raised when End Index is Out of Range

Slicing of tuple in Python will not raise an error, even if the given end index is out of range from the tuple.

# slicing will not throw an error, if end index is more than tuple limit
print("slicing will not throw an error, if end index is more than tuple limit")

shbytes_tuple=(0,1,2,3,4,5,6,7,8,9,10,11)
print(shbytes_tuple, type(shbytes_tuple))

print(shbytes_tuple[2:14])         # colon operator, start index 2, end index 14, default step by 1
print(shbytes_tuple[slice(2, 14)])  # slice method, start index 2, end index 14, default step by 1

# Output
# slicing will not throw an error, if end index is more than tuple limit
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) <class 'tuple'>
# (2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
# (2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

In this program, shbytes_tuple has total 12 elements and we are slicing on that tuple using colon (:) operator and slice() method. Both slicing methods, we are giving end index as 14, which is out of range for the tuple. Still, Slicing of tuple will not raise an error and will slice the tuple up-to the last element. By default, step value will be 1.

From the program output, all the elements from index 2 to the last index in tuple are taken in sliced tuple. No error raised even when the given end index was out of range from tuple.

Slicing of Tuple till the Last Element

For slicing of tuple till the last element with colon (:) operator, we don’t need to provide end index. By default end index equal to the total number of elements in the tuple.

But for slicing of tuple till the last element with slice() method, we need to provide end index. We can provide end index either with positive index or with negative index. But with negative index, we will not be able to get the last element in the tuple. This is because tuple is sliced from start to end - 1 index only.

# slicing value from index 1 to end of the tuple
print("slicing value from index 1 to end of the tuple")

shbytes_tuple=(0,1,2,3,4,5,6,7,8,9,10,11)
print(shbytes_tuple, type(shbytes_tuple))

print(shbytes_tuple[1:])          # colon operator, start index 1, default to end of tuple, default step by 1
print(shbytes_tuple[slice(1, -1)])   # step method, start index 1, negative end index, default step by 1
print(shbytes_tuple[slice(1, 12)])   # step method, start index 1, positive end index, default step by 1

# Output
# slicing value from index 1 to end of the tuple
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) <class 'tuple'>
# (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
# (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

In this program, we have defined a shbytes_tuple that has total 12 elements.

  • With colon (:) operator, we provide only start index and no need to provide end index. In this scenario, it returned all elements starting from index 2.
  • With slice() method we provided -1 (last element negative index). In this scenario, it returned elements with missing last element. Elements were taken from start to end -1 index only.
  • With slice() method we provide 12 (total number of elements in tuple) (positive indexing). In this scenario, it returned all elements starting from index 2.

Slicing of Tuple till the given End Index

For slicing of tuple till the given end index with colon (:) operator or with slice() method, in both cases we don’t need to provide start index. By default start index is the index 0. We can only provide end index either with positive index or with negative index.

# slicing value from index 0 to 3 of the tuple
print("slicing value from index 0 to 3 of the tuple")

shbytes_tuple=(0,1,2,3,4,5,6,7,8,9,10,11)
print(shbytes_tuple, type(shbytes_tuple))

print(shbytes_tuple[:4])        # colon operator, default start index 0, end index 4, default step by 1
print(shbytes_tuple[slice(4)])   # slice method, default start index 0, end index 4, default step by 1

# Output
# slicing value from index 0 to 3 of the tuple
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) <class 'tuple'>
# (0, 1, 2, 3)
# (0, 1, 2, 3)

In this program, with colon (:) operator and with slice() method in both cases we only provide end index and no need to provide start index. When only one parameter is given it is taken for end index.

From the program output, in both scenarios we got elements starting from index 0 (default value for start) till end index 3 (till end-1 index).

Slicing of Tuple with Negative End Index

# Negative slicing start from the right hand side from -1 index position
print("Negative slicing start from the right hand side from -1 index position")

shbytes_tuple=(0,1,2,3,4,5,6,7,8,9,10,11)
print(shbytes_tuple, type(shbytes_tuple))

print(shbytes_tuple[:-1])       # colon operator, default start index 0, end index -1, default step by 1
print(shbytes_tuple[slice(-1)])  # slice method, default start index 0, end index -1, default step by 1

# Output
# Negative slicing start from the right hand side from -1 index position
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) <class 'tuple'>
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

In this program, with colon (:) operator and with slice() method in both cases we only provide end index and no need to provide start index. Default start index is 0. When only one parameter is given it is taken for end index. Elements are taken from left to right even when end index is negative.

Slicing of Tuple with Negative Start and End Index

# slicing value will be start from -3 index to -2 index position
print("slicing value will be start from -3 index to -2 index position")

shbytes_tuple=(0,1,2,3,4,5,6,7,8,9,10,11)
print(shbytes_tuple, type(shbytes_tuple))

print(shbytes_tuple[-3:-1])     # colon operator, negative start index, end index, default step by 1
print(shbytes_tuple[slice(-3,-1)])  # slice method, negative start index, end index, default step by 1

# Output
# slicing value will be start from -3 index to -2 index position
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) <class 'tuple'>
# (9, 10)
# (9, 10)

Elements are taken from left to right even when start and end index are negative.

Slicing from Left to Right with Positive Step

# slicing value from index 0 and after second step each of the element from left
print("slicing value from index 0 and after second step each of the element from left")

shbytes_tuple=(0,1,2,3,4,5,6,7,8,9,10,11)
print(shbytes_tuple, type(shbytes_tuple))

print(shbytes_tuple[::2])          # colon operator, default start and end index, positive step 2
print(shbytes_tuple[slice(0, -1, 2)])  # slice method, start index 0 and end index -1, positive step 2

# Output
# slicing value from index 0 and after second step each of the element from left
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) <class 'tuple'>
# (0, 2, 4, 6, 8, 10)
# (0, 2, 4, 6, 8, 10)
  • Slicing of tuple with colon (:) operator, we are not using start and end index but only step value 2. Note – empty colon for start and end.
  • Slicing of tuple with slice() method, we need to provide start and end index with step value 2.
  • step value 2 means, indices will jump 2 steps (in left to right direction) to take the next element.

From the program output, in sliced tuple we got alternate elements from left to right direction. Because of positive step elements are taken in left to right direction.

Slicing from Right to Left with Negative Step

  • Slicing with negative step can also be used to reverse the tuple elements.
# slicing value from index -1 and after second step each of the element from right
print("slicing value from index -1 and after second step each of the element from right")

shbytes_tuple=(0,1,2,3,4,5,6,7,8,9,10,11)
print(shbytes_tuple, type(shbytes_tuple))

print(shbytes_tuple[::-2])            # colon operator, default start and end index, negative step -2
print(shbytes_tuple[slice(-1, 0, -2)])  # slice method, start index -1 and end index 0, negative step -2

# Output
# slicing value from index -1 and after second step each of the element from right
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) <class 'tuple'>
# (11, 9, 7, 5, 3, 1)
# (11, 9, 7, 5, 3, 1)
  • Slicing of tuple with colon (:) operator, we are not using start and end index but only step value -2. Note – empty colon for start and end.
  • Slicing of tuple with slice() method, we need to provide start and end index with step value -2.
  • step value -2 means, indices will jump 2 steps (in right to left direction) to take the next element.

From the program output, in sliced tuple we got alternate elements from right to left direction. Because of negative step elements are taken in right to left direction.

Conclusion

Python’s tuple slicing techniques offer a powerful and flexible way to extract specific elements or sub-tuples from a given tuple. By understanding various slicing methods, including handling out-of-range end indices without errors, slicing up to the last element, and using both positive and negative indices, you can manipulate tuple data with ease. Whether you are working with standard indexing or exploring reverse slicing with a negative step, Python provides robust tools for efficient data extraction. These slicing techniques allow for greater control and versatility in working with tuples, enhancing your ability to write more concise and effective code.

Code snippets and programs related to Slicing of Tuple in Python, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.

Tuple Slicing Interview Questions & Answers

Q: What happens if the start index is greater than the end index in a slice?

  • If step is positive and start index is greater than the stop index => The slice will return an empty tuple because Python slices elements from left to right (in case of positive step) by default.
numbers_tuple = (130, 220, 35, 46, 51)
# slice from left to right
result = numbers_tuple[3:1]  # Start index is greater than stop index
print(result)  # Empty tuple => ()
  • If step is negative => The slicing occurs from right to left.
numbers_tuple = (130, 220, 35, 46, 51)
# slice from right to left
result = numbers_tuple[3:1:-1]     # Start index is greater than stop index, negative step
print(result)  # Tuple elements => (46, 35)

Q: What will happen if we slice a tuple with a step of 0?

In Python, if we try to slice a tuple with a step of 0, it will raise a ValueError because a step of 0 would imply no movement in the index, leading to an infinite loop in theory.

numbers_tuple = (130, 220, 35, 46, 51)
sliced_tuple = numbers_tuple[::0]  # ValueError: slice step cannot be zero

Q: What is the difference between slicing a tuple and slicing a list in Python?

  • Slicing of tuple and slicing of list, both follow the same syntax and rules
  • The result of slicing a tuple is always a new tuple, and it does not affect the original tuple.
  • For lists, slicing also returns a new list, but the original list can still be modified.

Related Topics

  • Update List Elements | Modify Elements in Python List
    In Python, elements in a list can be updated or replaced by assigning a new value to an element’s index position. In previous articles, we covered accessing list elements by index, using the list index method to find an element’s index, and appending elements to a list. This article focuses on how to update elements…
  • Understanding Lists in Python: A Comprehensive Guide
    Lists in Python List is a core datatype in Python. Lists are sequences used to store elements (collection of data). Lists are similar to Arrays but are of dynamic size. It means the size of the list can be increased or decreased as we add or remove elements from the list. Understanding Python Lists: A…
  • Understand the Index Method in Python Tuples: Use Cases, Limitations, and Examples
    Elements in the tuple are stored based on their index positions. Python provides the index(arg) method to determine the index position of an element in a tuple. In previous article Access tuple elements by index in Python, we learned about accessing the tuple element at the given index position. In this article we will learn…
  • Tuples in Python: Operations, Definition & Examples
    Tuples in Python Python tuples is a sequence used to store elements (a collection of data). Similar to arrays and lists, tuples also store elements based on their index and can be accessed based on the index position. Understanding Python Tuples: A Core Datatype Tuples are core data types in Python, alongside list, set, and…
  • Slicing of Tuple in Python: Methods, Examples & Interview Questions
    Slicing of a tuple means extracting a part (or slice) of the tuple. In Python, tuple slicing can be done in two primary ways: In previous articles, we learned about Access Tuple Elements by Index in Python, How to Change Elements in a Tuple in Python and How to Remove Elements from a Tuple in Python.…

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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