Python: Append item to list N times

后端 未结 6 1144
礼貌的吻别
礼貌的吻别 2020-12-12 16:46

This seems like something Python would have a shortcut for. I want to append an item to a list N times, effectively doing this:

l = []
x = 0
for i in range(1         


        
相关标签:
6条回答
  • 2020-12-12 17:27

    For immutable data types:

    l = [0] * 100
    # [0, 0, 0, 0, 0, ...]
    
    l = ['foo'] * 100
    # ['foo', 'foo', 'foo', 'foo', ...]
    

    For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

    l = [{} for x in range(100)]
    

    (The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

    If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

    a = [1,2,3]
    b = [4,5,6]
    a.extend(b)
    # a is now [1,2,3,4,5,6]
    
    0 讨论(0)
  • 2020-12-12 17:30

    You could do this with a list comprehension

    l = [x for i in range(10)];
    
    0 讨论(0)
  • 2020-12-12 17:34

    Use extend to add a list comprehension to the end.

    l.extend([x for i in range(100)])
    

    See the Python docs for more information.

    0 讨论(0)
  • 2020-12-12 17:36
    l = []
    x = 0
    l.extend([x]*100)
    
    0 讨论(0)
  • 2020-12-12 17:40

    Itertools repeat combined with list extend.

    from itertools import repeat
    l = []
    l.extend(repeat(x, 100))
    
    0 讨论(0)
  • 2020-12-12 17:43

    I had to go another route for an assignment but this is what I ended up with.

    my_array += ([x] * repeated_times)
    
    0 讨论(0)
提交回复
热议问题