Creating a list in Python with multiple copies of a given object in a single line

前端 未结 6 1177
孤街浪徒
孤街浪徒 2020-12-03 04:56

Suppose I have a given Object (a string \"a\", a number - let\'s say 0, or a list [\'x\',\'y\'] )

I\'d like to create list containing many copies of thi

6条回答
  •  半阙折子戏
    2020-12-03 05:39

    If you want unique instances and like to golf, this is (slightly) shorter:

    L = [['x', 'y'] for _ in []*10]
    

    The crazy thing is that it's also (appreciably) faster:

    >>> timeit("[['x', 'y'] for _ in [0]*1000]", number=100000)   
    8.252447253966238                                             
    >>> timeit("[['x', 'y'] for _ in range(1000)]", number=100000)
    9.461477918957826
    

提交回复
热议问题