Python Tuple

Estimated reading: 2 minutes 635 views

Tuple Overview

Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.
					first = (1,2,3,45,)

Tuple Access Value

You can access tuple items by referring to the index number, inside square brackets:

					my_tuple = ('p','e','r','m','i','t')

Tuple Negative indexing

The Below Code will show the negative indexing for Tuple

					my_tuple = ('p','e','r','m','i','t')
# Output: 't'
# Output: 'p'

Tuple Slicing

Tuple Slicing is used to get the value between two range.

					my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
# Output: ('r', 'o', 'g')

# elements beginning to 2nd
# Output: ('p', 'r')


# elements 8th to end
# Output: ('i', 'z')

# elements beginning to end
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Looping Tuple Without indexing

					tup1 = (1,2,3,4,5,6)
for i in tup1:

You can loop through the tuple items by using a for loop.

Tuple Looping With Index

You can also loop through the tuple items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

					tup1 = (1,2,3,4,5,6)
for i in tup1:

Join Tuples

To join two or more tuples you can use the + operator:

					tup1 = (1,2,3,4,5,6)
tup2 = (6,7,8)
res2 = tup1 + tup2

Multiply Tuples

If you want to multiply the content of a tuple a given number of times, you can use the * operator:

					print(("Repeat",) * 4)

Tuple count()

Returns the number of times a specified value occurs in a tuple
					my_tuple = ('a','p','p','l','e',)

# Count
# Output: 2

Tuple index()

Searches the tuple for a specified value and returns the position of where it was found , if not found it will give valueError
					my_tuple = ('a','p','p','l','e',)

Leave a Comment