Codied To Clipboard !
Home > Notes > python
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)
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])
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 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
first = (1,2,3,4,5) for i in first: print(i)
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])
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)
If you want to multiply the content of a tuple a given number of times, you can use the * operator:
print(("Repeat") * 4)
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
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"))