Search code examples
pythonlistlist-comprehension

How do I append values to different lists at one time, in one line?


I'm a beginner to python, but I can't find anything on the internet to help me with this problem:

I want to append different values to 2 different lists at once (the actual problem is more complex than this but I just need to know the right syntax so I'm simplifying it)

test1= []
test2= []
[test1.append(1) and test2.append(2) for i in range (10)]

this doesn't append to both lists, how do I make that happen?


Solution

  • If your specific example is what you want, use argument unpacking to assign multiple values at once:

    test1, test2 = [1] * 10, [2] * 10
    

    You can also use the zip(*x) idiom to transpose a 2-column list:

    test1, test2, map(list, zip(*[[1, 2]] * 10))
    

    If you're OK with having tuples instead of lists, you can omit the map(list, ...) wrapper.

    The best way I know of having a comprehension with side-effects is using collections.deque with a size of zero, so it runs the iterator but does not store any results:

    from collections import deque
    
    test1, test2 = [], []
    deque(((test1.append(1), test2.append(2)) for _ in range(10)), maxlen=0)
    

    The generator creates tuples (None, None) every time (since list.append returns None), which the deque promptly discards.