Example:
tuple = ("python", "includehelp", 43, 54.23)
Repeating tuples N times
We are given a tuple with integer values and an integer N. We need to create a Python program to create a new tuple that will contain the given tuple repeated N times.
Input:
tup1 = (2, 9), N = 5
Output:
((2, 9) ,(2, 9) ,(2, 9) ,(2, 9) ,(2, 9))
To create duplicate tuples N times, we need to create an empty tuple and concatenate the values of the tuple to it N times. Python provides some methods that can help to ease the programmer's work performing these tasks, let's learn them here.
Method 1:
One method to perform the task is by using the multiplication operator "*" which will multiply the tuples and create a new tuple with the values the tuple repeated N times.
Output:
Method 2:
Another method to solve the problem is by using the repeat() method present in Python's itertools library. This will return a list consisting of the tuple repeated N times. Then we will convert it into a tuple using the tuple() method.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer