Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading