Python Tuple Operations – Python Tutorial

2 weeks ago codedestine 0

Python Tuple Operations : Python has various types of common sequence operations that can be applied on tuple.

In this tutorial, we will learn about different python tuple operations :

  1. Tuple Concatenation
  2. Tuple Repetition
  3. Tuple Contains
  4. Tuple Not Contains
  5. Tuple Length
  6. Tuple Min & Max

Python Tuple Operations

Tuple Concatenation

We can use addition ( + ) operator to join two tuples together to create a new tuple.

# create first tuple object and assign it to variable f f = ('Jan','Feb','Mar') # create second tuple object and assign it to variable s s = ('Apr','May','Jun') # example of concatenation concatenate = f + s print(concatenate)

Tuple Repetition

We can use multiplication ( * ) operator to join same tuple multiple times to create a new tuple.

# create tuple object and assign it to variable f f = ('Jan','Feb','Mar') # example of repetition repetition = f * 3 print(repetition)

Tuple Contains

We can use in operator to check, if a given item is present in the tuple or not. If present then return True otherwise return False.

# create tuple object and assign it to variable f f = ('Jan','Feb','Mar') # example of contains contains = 'Jan' in f print(contains)

Tuple Not Contains

We can use not in operator to check, if a given item is present in the tuple or not. If present then return False otherwise return True.

# create tuple object and assign it to variable f f = ('Jan','Feb','Mar') # example of not contains not_contain = 'Jan' not in f print(not_contain)

Tuple Length

We can use len() (Syntax: len(< Tuple Object >) ) function to get the length of a tuple. For example:

# create tuple object and assign it to variable t t = ('Jan','Feb','Mar') # call len() method to get length of the tuple t and assign it to variable length length = len(t) # print the value of variable length print(length)

Tuple Min & Max

We can use min() (Syntax: min(< Tuple Object >) ) and max() (Syntax: max(< Tuple Object >) ) function to get minimum and maximum element in the tuple. For example:

# create tuple object and assign it to variable t t = (1,2,3) # call min() method to get minimum element in the tuple t and assign it to variable minimum minimum = min(t) # print the value of variable minimum print(minimum) # call max() method to get maximum element in the tuple t and assign it to variable maximum maximum = max(t) # print the value of variable maximum print(maximum)

References :-

  1. Tuple Methods Docs

That’s all for Python Tuple Operations. If you liked it, please share your thoughts in comments section and share it with others too.

Previous
Next