Skip to content Skip to sidebar Skip to footer

How Do You Create A List Of Repeated Tuples In Python?

Say I have a list of tuples, I extract the first tuple from this list and then want to create a new list that simply takes the first tuple and repeats it n times creating a list of

Solution 1:

Since tuples are immutable you may be able to do:

lst = [tuples[0]]
repeated = lst * 10# create a list of the first tuple repeated 10 times

If they contain mutable objects changes in any of them will reflect in all of them, since these are the same objects repeated.

Solution 2:

Let say that you have a list like this one:

list_of_tuples = [('foo', 'bar'), ('baz', 'qux')]

If you want to repeat the first tuple n times, you can use itertools.repeat

import itertools
itertools.repeat(list_of_tuples[0], n)

where n is the number of times you want the first tuple to be repeated. itertools.repeat will return a generator.

Post a Comment for "How Do You Create A List Of Repeated Tuples In Python?"