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

前端 未结 6 1170
孤街浪徒
孤街浪徒 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条回答
  •  Happy的楠姐
    2020-12-03 05:29

    You can use the * operator :

    L = ["a"] * 10
    L = [0] * 10
    L = [["x", "y"]] * 10
    

    Be careful this create N copies of the same item, meaning that in the third case you create a list containing N references to the ["x", "y"] list ; changing L[0][0] for example will modify all other copies as well:

    >>> L = [["x", "y"]] * 3
    >>> L
    [['x', 'y'], ['x', 'y'], ['x', 'y']]
    >>> L[0][0] = "z"
    [['z', 'y'], ['z', 'y'], ['z', 'y']]
    

    In this case you might want to use a list comprehension:

    L = [["x", "y"] for i in range(10)]
    

提交回复
热议问题