Python Tuples

A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

Create Tuple

tup1 = ('hello', 'world', 20, 2020)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
tup_empty = ()
# tuple containing a single value you have to include a comma, even though there is only one value
tup_single_elem = (50,)
# without the comma tuple element convert into string or int
tup_single_elem_int = (50)
print("printing contents: ",tup1,tup2,tup3,tup_empty,tup_single_elem,tup_single_elem_int)
print("printing types:",type(tup1),type(tup2),type(tup3),type(tup_empty),type(tup_single_elem),type(tup_single_elem_int))

#output: printing contents:  ('hello', 'world', 20, 2020) (1, 2, 3, 4, 5) ('a', 'b', 'c', 'd') () (50,) 50
#output: printing types:  <class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'int'>

Tuples – count()

The purpose of the method count is to find how many times a specific element appears in a tuple.

x=(1,5,5,6,7,9)
z=x.count(5)
print(z)
# output; 2

Tuples- Index ()

Searches the tuple for a specified value and returns the position of where it was found.

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = thistuple.index(8)
print(x)
#output- 6

cars = (“toyota”, “honda”, “nissan”)
x = cars.index(2)
print(x)

#output- nissan