Search code examples
pythonlist-comprehension

How to apply list comprehension for two variables


I am trying to understand list comprehention so that I can make the code on a project I'm working on more efficient. I found a simple example which is easy to understand:

L = []
for i in range (1, 10):
    if i%3 == 0:
        L.append (i)
print(L)

[3, 6, 9]

And this is the code with list comprehension:

L = [i for i in range (1, 10) if i%3 == 0]
print(L)

I tried to apply what I have just learned to this code but I'm having trouble figuring out how to do that.

L = []
M = []
for i in range (1, 10):
    if i%3 == 0:
        L.append (i)
        M.append(i*2)
print(L,M)

[3, 6, 9] [6, 12, 18]

The following is not valid Python, but illustrates what I'm looking for:

[L,M] = [i for i in range (1, 10) if i%3 == 0, i*2 for i in range (1, 10) if i%3 == 0]

Solution

  • The syntax of the list comprehension that you are looking for is far simpler than you imagine:

    x = [(i, i*2) for i in range (1, 1000) if i%3 == 0]
    print(x)
    

    Now for the last bit where you are after two lists: L,M.

    What you need are the answers to this question

    So, for example:

    L, M = zip(*x)
    

    Also see this link which dynamically shows how to transform between for loop and list comprehension.