Python Tuple – Indexing and Slicing


Tuple Indexing

Indexing in the tuple works in the same way as in the List. Each Item is assigned the index position that starts with 0. We can access each item of tuple by passing the index position in the square brackets.

Example:

emp_details = (‘Brad’,’Lee’,’Sales’,380,250000,True,’New York’,’USA’,’Developer’,’Python’)

Python Tuple - Indexing and Slicing

Few Examples:

In [1]:
emp_details = ('Brad','Lee','Sales',380,250000,True)

Check what is at position 0.

In [2]:
print(emp_details[0])
Brad

Position 4.

In [3]:
print(emp_details[4])
250000

Tuple Slicing

When we need to extract more than one item from the tuple, then slicing is performed. While performing slicing, we can pass three optional parameters in the square brackets([]) separated by a colon(:):

Tuple[StartPosition:EndPosition:Jump]

StartPosition Item at which we want to start. Default is the first character.
EndPosition Up to which item we want to go(Note: this is up to, the item at this specific location will not be included). Default is the last last.
Jump The number of items we want to jump. Default is 1 means it will not jump anything.

When we don’t use a colon(:) then the specified argument is considered as the position of an item.

Let us understand index positions with some examples:

Only using start to end.

In [1]:
emp_details = ('Brad','Lee','Sales',380,250000,True,'New York','USA','Developer','Python')
print(emp_details[0:])
('Brad', 'Lee', 'Sales', 380, 250000, True, 'New York', 'USA', 'Developer', 'Python')

Start with 3 to end.

In [2]:
print(emp_details[3:])
(380, 250000, True, 'New York', 'USA', 'Developer', 'Python')

Go up to 3. Note: Item at position 3 will not be included.

In [3]:
print(emp_details[:3])
('Brad', 'Lee', 'Sales')

Include all jumping a character.

In [4]:
print(emp_details[::2])
('Brad', 'Sales', 250000, 'New York', 'Developer')

Start at 2 up to 8.

In [5]:
print(emp_details[2:8])
('Sales', 380, 250000, True, 'New York', 'USA')

Start with 1 up to 8 with jump of 3.

In [6]:
print(emp_details[1:8:3])
('Lee', 250000, 'USA')

Negative Indexing

We can also use negative indexing. The last item is assigned with the index position of -1. It keeps on increasing in the negative order till the first item. If we want to traverse backward, we can use jump as a negative number. Example -1.

Negative Index Positions:

Example:

emp_details = (‘Brad’,’Lee’,’Sales’,380,250000,True,’New York’,’USA’,’Developer’,’Python’)

Tuple Negative Indexing

Let us understand with some examples:

Item at -2 position.

In [1]:
emp_details = ('Brad','Lee','Sales',380,250000,True,'New York','USA','Developer','Python')
print(emp_details[-2])
Developer

This will not work because the default jump size is 1 which is positive but to traverse backward we need a negative jump size.

In [2]:
print(emp_details[-2:-6])
()

Traversing from -2 uptill -6 with jump of -1.

In [3]:
print(emp_details[-2:-6:-1])
('Developer', 'USA', 'New York', True)

Traversing from -5 to -2 with a positive jump i.e. default 1.

In [4]:
print(emp_details[-5:-2])
(True, 'New York', 'USA')

We can use this approach to reverse the tuple.

In [5]:
print(emp_details[::-1])
('Python', 'Developer', 'USA', 'New York', True, 250000, 380, 'Sales', 'Lee', 'Brad')

Check if an item exists in Tuple

To check whether an item exists inside the tuple or not, we use the membership operator in.

In [1]:
emp_details = ('Brad','Lee','Sales',380,250000,True)
if ("Brad" in emp_details):
    print("Welcome, Brad!")
Welcome, Brad!

As Steve is not present, so nothing gets printed.

In [2]:
emp_details = ('Brad','Lee','Sales',380,250000,True)
if ("Steve" in emp_details):
    print("Welcome, Steve!")

Index out of range error

If we try to access any index position where no item is present, then we get ‘index out of range’ error.

If we try to access item at index 2, we get index out of range error.

In [1]:
emp_details = ['Brad','Lee']
print(emp_details[2])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-1-bde5aa4163cd> in <module>
      1 emp_details = ['Brad','Lee']
----> 2 print(emp_details[2])

IndexError: list index out of range

References

  1. Accessing Tuple Elements in Python
  2. Tuple Indexing