Q:

Python program to repeat tuples N times

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

# Python program to repeat tuples N times
  
# Initializing and printing tuple 
myTup = (32, 8)
print("The elements of the given tuple are " + str(myTup))
N = 4
  
# Repeating Tuple N times
repeatTuple = ((myTup, ) * N)
  
# printing result
print("The tuple repeated N times is : " + str(repeatTuple))

Output:

The elements of the given tuple are (32, 8)
The tuple repeated N times is : ((32, 8), (32, 8), (32, 8), (32, 8))

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.

# Python program to repeat tuples N times
  
import itertools
  
# Initializing and printing tuple 
myTup = (32, 8)
print("The elements of the given tuple are " + str(myTup))
N = 4
  
# Repeating Tuple N times
repeatTuple = tuple(itertools.repeat(myTup, N))
  
# Printing result
print("The tuple repeated N times is " + str(repeatTuple))

Output:

The elements of the given tuple are (32, 8)
The tuple repeated N times is ((32, 8), (32, 8), (32, 8), (32, 8))

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to check if two lists of tuples are... >>
<< Python program to flatten tuple list to string...