Access tuple in Python

We access tuple in Python by indexing such as negative index or positive index in the square brackets. The process of index is the same as index in List. Remember, tuples are immutable, meaning once they are created, their elements cannot be changed. You can only access and read the elements of a tuple. Here how can access tuple in Python.

For example:

myCar=(('Toyota','Mitsubishi',12,3,True))
print(myCar[3])
#output: 3

Negative Index

We can index in tuple by negative value to the position.

For example:

Negative index start from the end of tuple to the beginning. The last item in tuple is located on index (-1). 

myCar=(('Toyota','Mitsubishi',12,3,True))
print(myCar[-3])
#output: 12

Range of Index

Tuple can be indexed by ranging from the beginning of the position to the end of the position.

For example:

myCar=(('Toyota','Mitsubishi',12,3))
print(myCar[2:4])
#output: (12, 3)  

Left value empty

This will collect items only from index 0 to the position on the right.

For example:

myCar=(('Toyota','Mitsubishi',12,3))
print(myCar[:3])
#output:('Toyota', 'Mitsubishi', 12)

Right value empty

This will collect items only from the index on the left to end on tuple.

For example:

myCar=(('Toyota','Mitsubishi',12,3))
print(myCar[3:])
#output:(3,)

freecode4learn.com

Leave a Reply