Reputation: 57
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]
Upvotes: 0
Views: 248
Reputation: 57
Thank you for your suggestions! They both helped me to resolve the knot in my head, so it's a bit unfair to have to give the green check to only one of them.
At first, Mortz' code made a lot of sense to me because it was very close to my 'solution'. After some crunching, I understood quamranas solution too, which seemed more complicated at first.
Writing it down like this and following closely what happens helped me understand. It may seem trivial to many, but maybe it helps someone who is as slow as me.
x = [(i, i*2) for i in range (1, 10) if i%3 == 0]
#i = 3
#x = [(3,6)]
#i = 6
#x = [(3,6),(6,12)]
#i = 9
#x = [(3,6),(6,12),(9,18)]
print(x)
L,M = zip(*x)
print(L,M)
#(3, 6, 9) (6, 12, 18)
Upvotes: 1
Reputation: 4939
You want 2 list comprehensions, one of which produces L
and the other M
. You are almost there, except for a couple of brackets
[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]]
In fact, you don't need to put L
and M
in a list - this works just fine
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]]
print(L)
# [3, 6, 9]
print(M)
# [6, 12, 18]
Upvotes: 1
Reputation: 39404
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.
Upvotes: 2