Home > other >  Can i add two elements at once in a list comprehension?
Can i add two elements at once in a list comprehension?

Time:10-16

The output i want:

[[(1,1)], [(2,2)], [(2,2)], [(4,4)], [(3,3)], [(6,6)]]

This is the code that does not work:

mylist = [[[(x,x)], [(x*2,x*2)]] for x in range(1, 4)]

I know i could use:

mylist = []
[mylist.extend([[(x,x)], [(x*2,x*2)]]) for x in range(1, 4)]

But is there a way to write this in one line? I my script the code is a bit more complicated, the example above is just to show the principe. Therefore it makes no sense.

CodePudding user response:

Use a nested list comprehension:

mylist = [y for x in range(1, 4) for y in ([x], [x * 2])]
print(mylist)

Result:

[[1], [2], [2], [4], [3], [6]]

CodePudding user response:

you can use builtin itertools

>>> from itertools import chain

>>> list(chain.from_iterable([[(x, x)], [(x*2, x*2)]] for x in range(1, 4)))
[[(1, 1)], [(2, 2)], [(2, 2)], [(4, 4)], [(3, 3)], [(6, 6)]]

CodePudding user response:

If you want to solve this with a list comprehension without using itertools.chain. from_iterable, you can use nested list comprehension to unpack the list that you create for each iteration.

This is done as [item for sublist in list for item in sublist]

Applied here -

[j for x in range(1, 4) for j in ([(x,x)], [(x*2,x*2)])]
[[(1, 1)], [(2, 2)], [(2, 2)], [(4, 4)], [(3, 3)], [(6, 6)]]

This is equivalent to using the unpacking operator * over the [[(x,x)], [(x*2,x*2)]], but since that doesn't work in a list comprehension, this is a good way to do the same.

  • Related