ruh
ruh

Reputation: 139

Python - Duplicate Tuples in an orderly fashion

I would like to find a way to duplicate tuples in my list but in a orderly fashion. Meaning:

Assuming:

a = [('c','v','t'),(1,2,3)] 

and Assuming three duplicates, I am looking for a way to get this:

a = [('c','v','t'),('c','v','t'),('c','v','t'),(1,2,3),(1,2,3),(1,2,3)] 

So far I use list comprehension

[item*3 for item in a]

Howver, it breaks the tuples:

out = [('c', 'v', 't', 'c', 'v', 't', 'c', 'v', 't'), (1, 2, 3, 1, 2, 3, 1, 2, 3)]

Upvotes: 0

Views: 62

Answers (3)

pylang
pylang

Reputation: 44545

itertools.repeat is your friend.

import itertools as it


a = [("c", "v", "t"), (1, 2, 3)] 

list(it.chain(*zip(*it.repeat(a, 3))))
# [('c', 'v', 't'), ('c', 'v', 't'), ('c', 'v', 't'), (1, 2, 3), (1, 2, 3), (1, 2, 3)]

Upvotes: 1

internet_user
internet_user

Reputation: 3279

You can use a list comprehension:

dup_num = 3
list1 = [('c', 'v', 't'), (1, 2, 3)]
list2 = [tup2 for tup in list1 for tup2 in [tup] * 3]

But I don't really like that.

You can also use a for loop:

list2 = []
for tup in list1:
  list2.extend([tup] * 3)

Upvotes: 0

usernamenotfound
usernamenotfound

Reputation: 1580

this should work:

[y for y in a for i in range(3)]

Using two loops prevents the issue you have

Upvotes: 4

Related Questions