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,)
print(first)
				
			

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')
print(my_tuple[0])
print(my_tuple[5])
				
			

Tuple Negative indexing

The Below Code will show the negative indexing for Tuple

				
					my_tuple = ('p','e','r','m','i','t')
# Output: 't'
#print(my_tuple[-1])
#print(len(my_tuple))
# Output: 'p'
#print(my_tuple[-6])
				
			

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')
#print(my_tuple[1:4])

# elements beginning to 2nd
# Output: ('p', 'r')
#print(my_tuple[:-4])

#print(my_tuple[4:])

# elements 8th to end
# Output: ('i', 'z')
#print(my_tuple[7:])

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

Looping Tuple Without indexing

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

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:
  print(tup1[i])
				
			

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
print(res2)
				
			

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
#print(my_tuple.count('p'))
				
			

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',)
print(my_tuple.index('z'))
				
			

Leave a Comment

CONTENTS