Tuple in Python

Tuple are ordered set/collection of data separated by comma. Like list they are also sequence type but immutable .

Note: All common sequence operation can be performed on tuple.

Example:

#Creating tuple using paranthesis:

var =("Geeks", "for", "Geeks")

print(var)

#Creating tuple using tuple as a constructor:

tuple_constructor =tuple(("dsa", "developement", "deep learning"))

print(tuple_constructor)

We can also write

t="a","b","c"

print(t)

#Output:

('a','b','c')

Note: Always use a paranthesis while passing tuple as an argument to function

Example:

name="Tim"

age=10

print((name,age,2020))

Indexing a Tuple:

Indexing a tuple works same as indexing a list i.e It is used to refer to a particular item present in tuple , considering the counting starts from 0.

Example:

a=(1,3,4)

print(a[0])

#Output:

1

Unpacking in Tuple:

When we create a tuple, we normally assign values to it. This is called “packing” a tuple.When we create a tuple, we normally assign values to it. This is called “packing” a tuple.

Example:

fruits = ("apple", "banana", "cherry")

green, yellow, red= fruits

print(green)
print(yellow)
print(red)

Here fruits is a tuple and we have unpacked its value into three variables green , yellow and red.

Note: Since tuples are immutable ( do not let the data change) so they protect the integrity of data . Also they use less memory as compare to list. Since List are mutable so we generally put homogenous items in list and as tuples are immutable so heterogenous item in it.

Common Operations on tuple:

Concatenation in Tuple:

To concatenate tuple we will use “+” operator

Example:

tuple1 =(0, 1, 2, 3)

tuple2 =('python', 'geek')

# Concatenating above two

print(tuple1 +tuple2)

#Output:

(0, 1, 2, 3, ‘python’, ‘geek’)

Repetition of Tuple:

Using this we can create a multiple of same element using the same element in that tuple:

Example:

tuple3 =('python',)*3

print(tuple3)

#Output:

('python', 'python', 'python')

Slicing Tuple:

Slicing tuple means dividing tuple into small tuple using indexing method.

Example:

tuple1 =(0,1, 2, 3)

print(tuple1[1:])

print(tuple1[::-1])

#Output:

(1,2,3)

(3,2,1,0)

Deleting a tuple:

It is not possible to delete individual element but we can delete the whole tuple using del keyword.

Example:

tuple3 =( 0, 1)

deltuple3

print(tuple3)

#Output:

NameError: name 'tuple3' is not defined

Length of Tuple:

Using len keyword length of tuple can be determined.

Example:

tuple7 =('python', 'geek')

print(len(tuple7))

#Output:

2

Nested Tuple:

Nested tuple means tuple inside tuple.

Example:

x =(0, 1, 2, 3)

y =('python', 'geek')

z =(x, y)

print(z)

#Output:

((0,1,2,3),('python','geek'))



Leave a Reply

Your email address will not be published. Required fields are marked *