Python | Repeating tuples N times

Sometimes, while working with data, we might have a problem in which we need to replicate, i.e construct duplicates of tuples. This is important application in many domains of computer programming. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using * operator
The multiplication operator can be used to construct the duplicates of a container. This also can be extended to tuples even though tuples are immutable.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Repeating tuples N times
# using * operator
  
# initialize tuple 
test_tup = (1, 3)
  
# printing original tuple 
print("The original tuple : " + str(test_tup))
  
# initialize N 
N = 4
  
# Repeating tuples N times
# using * operator
res = ((test_tup, ) * N)
  
# printing result
print("The duplicated tuple elements are : " + str(res))

chevron_right


Output :



The original tuple : (1, 3)
The duplicated tuple elements are : ((1, 3), (1, 3), (1, 3), (1, 3))

 

Method #2 : Using repeat()
The internal function of itertools library, repeat() can be used to achieve the solution to the above problem.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Repeating tuples N times
# using repeat()
from itertools import repeat
  
# initialize tuple 
test_tup = (1, 3)
  
# printing original tuple 
print("The original tuple : " + str(test_tup))
  
# initialize N 
N = 4
  
# Repeating tuples N times
# using repeat()
res = tuple(repeat(test_tup, N))
  
# printing result
print("The duplicated tuple elements are : " + str(res))

chevron_right


Output :

The original tuple : (1, 3)
The duplicated tuple elements are : ((1, 3), (1, 3), (1, 3), (1, 3))



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.