Home > Notes > python

Python Tuple

python

Python Variable
Python Conditional statement
Python loops
Python List
Python Tuple
Python String
Python Set
Python Dictionary
Python Functions
Python Exceptions
Python File Operation
Python Map
Python Lambda
Python Filter
Python OOPS

Python Tuple

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,4,5)
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))
print(my_tuple[-6]) #p

Tuple Slicing

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

my_tuple = ("p","e","r","m","i","t")
print(my_tuple[1:4]) # ["e","r","m"]

Looping Tuple Without indexing

Looping Tuple Without indexing

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

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

first = (1,2,3,4,5)
for i in first:
 print(first[i])

Join Tuples

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

first = (1,2,3,4,5)
second = (8,9,7,6,5)
res1 = first+second
print(res1)

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