Operation on Tuple

There are some basic operations which can be performed on tuple.

Below is the list of basic operation

Finding Length
Concatenation
Repetition
Membership
Iteration

Finding length or number of elements inside a tuple

Use len() function to find number of elements inside a tuple

Exmple

tup = (1,2,3,4,5,6)
print('Number of elements:',len(tup))

Output

Number of elements: 6

Concatenate or joining two tuples

We can concatenate or join two tuples and save the result in a new tuple

Example

tup1 = (1,2,3)
tup2 = (4,5,6)
tup3 = tup1 + tup2
print(tup3)

Below output show elements inside new tuple

(1, 2, 3, 4, 5, 6)

Membership

Searching whether an element is a member of a tuple or not. Use ‘in’ and ‘not in’ operator

Example 1

tup = (10,20,30,40,50,60)
v = 60
print(v in tup)

Output

True

Example 2

tup = (10,20,30,40,50,60)
v = 70
print(v not in tup)

Output

True

Example 3

tup = (10,20,30,40,50,60)
v = 60
print(v not in tup)

Output

False

Repetition

Repeating elements inside a tuple

Example 1

tup = (1,2,3)
tup1 = tup*2
print(tup1)

Output

(1, 2, 3, 1, 2, 3)

Example 2

tup = ('Pyhton','Programming')
tup1 = tup*4
print(tup1)

Output

('Pyhton', 'Programming', 'Pyhton', 'Programming', 'Pyhton', 'Programming', 'Pyhton', 'Programming')

Iteration

Using while and for loop to display elements from a tuple

Example : While Loop

tup = (1,2,3,4,5)
l = len(tup)
i = 0
while i < l:
    print(tup[i])
    i+=1

Output

1
2
3
4
5

Example : For loop

tup = (1,2,3,4,5)
for t in tup:
    print(t)

Output

1
2
3
4
5
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s