How do you create a list of repeated tuples in Python?

前端 未结 2 1082
旧时难觅i
旧时难觅i 2021-01-29 14:13

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

相关标签:
2条回答
  • 2021-01-29 14:29

    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.

    0 讨论(0)
  • 2021-01-29 14:37

    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.

    0 讨论(0)
提交回复
热议问题