Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define duplicate items in a Python tuple?

What are some good ways to define a tuple consisting of integers where the number of occurrences of each item is known ?

For example,

I want to define a tuple with 3 2's, 2 4's and 1, 3, 5 occur once.

For this, I can always go the manual way :

foo = (1, 2, 2, 2, 3, 4, 4, 5)

However, this becomes a bit messy when the number of items in the list is large. So, I want to know what are some ways to automate the task of generating the desired number of duplicates of each item.

like image 942
Kshitij Saraogi Avatar asked Sep 13 '25 04:09

Kshitij Saraogi


1 Answers

You can do it like this:

>>> (1,) * 1 + (2,) * 3 + (4,) * 2 + (5,) * 1
(1, 2, 2, 2, 4, 4, 5)
like image 148
Dan D. Avatar answered Sep 15 '25 18:09

Dan D.