Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. List, Tuples and Dictiona...
  5. Tuples
  6. Tuple Operations

Tuple Operations

Concatenation

  • Concatenates two tuples
  •  Concatenation is done by + operator

Example

>>> t1 = (2,4,1)
>>> t2 = (10,1,20)
>>> t3 = t1+t2
>>> print(t3)
(2, 4, 1, 10, 1, 20)

Repetition

  • Repetition operator works as: repeats the tuples, a given number of times
  • Repetition is performed by the * operator in python

Example

>>> t1 = ("python")
>>> t1 * 2
>>> print(t1 * 2)
pythonpython
>>> t2 = (2,3)
>>> t3 = (t2) *3
>>> print(t3)
(2, 3, 2, 3, 2, 3)

in operator

  • in operator tells the user that the given element exists in the tuple or not
  • It gives a Boolean output, that is TRUE or FALSE
  • If the given input exists in the tuple, it gives TRUE as output, otherwise FALSE

Example

>>> t1 = (20,10, 5,3,90)
>>> 10 in t1
True
>>> 15 in t1
False
>>> t1 = ('python', 'chemistry', 'maths')
>>> 'python' in t1
True
>>> 'abc' in t1
False

Comparison operator (==, !=)

  • == operator compares two tuples and output true if two tuples are same else output false
  • != operator compares two tuples and output true if two tuples are not equal else output false

Example

>>> tuple1 = (1,2,3)
>>> tuple2 = ('a','b','c')
>>> tuple1 == tuple2
False
>>> tuple1 != tuple2
True

Iteration

Iteration in tuple can be done with for and while loop

Example 1

t1 = (3,1,4,10)
for x in t1:
	print(x)

Output

3
1
4
10

Example 2

t1 = (3,1,4,10)
for x in range(len(t1)):
	print(t1[x])

Output

3
1
4
10

Example 3

t1 = (3,1,4,10)
i=0
while(i<len(t1)):
	print(t1[i])
	i=i+1

Output

3
1
4
10

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments