Slice tuple Python | Example code

Use the [] operator on the tuple to Slice tuple in Python. If used a positive number, it slice that index from the tuple counting from the left. Or if its negative number, it fetches that index from the tuple counting from the right.

If you want to get a part of the tuple, use the slicing operator.

 [start:stop:step]. 

Read: Slice notation

Example Slice tuple Python

Simple example code.

If we don’t mention the start value the range by default starts from the first term.

my_tuple = ('A', 'B', 'C', 'D')

print(my_tuple[1])

print(my_tuple[-1])

Output:

Slice tuple Python

Ues tuple[start:stop] the start index is inclusive and the stop index

my_tuple = ('A', 'B', 'C', 'D', 'E')

res = my_tuple[3:5]

print(res)

Output: (‘D’, ‘E’)

If stop value not used then range by default ends at the last term.

my_tuple = ('A', 'B', 'C', 'D', 'E')

res = my_tuple[1:]

print(res)

Output: (‘B’, ‘C’, ‘D’, ‘E’)

Do comment if you have any doubts and suggestions on this Python tuple topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.