Coool Python List Comprehension

Cooool Python List Comprehension..

When we need to build a new list from existing list, lets say you have list of numbers from 1 to 10 as shown below. You need to build a separate list contains only even numbers from test_list, what to do?

test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_list = []
for element in test_list:
    if element % 2 == 0:
print even_list

come-on its not C we are not learning . Its pythonnn !!

So how do we make above condense above code to one line ? Not kidding.
Lime light on “list comprehension” please. Python supports expressions inside list, helps a lot to build lists
But limited, Its ok J

[element for element in test_list if element % 2 == 0]    

Just print the above line python shell see the even list.

This is fine for single for loop what if your list building logic contains multiple contains multiple loops and conditions? That works tooooo...

Find all the possible combination of three colors in two lists?

list_one = ["yellow", "white", "black"]
list_two = ["red", "blue", "green"]
[(x, y) for x in list_one for y in list_two]

Output :
[('yellow', 'red'), ('yellow', 'blue'), ('yellow', 'green'), ('white', 'red'), ('white', 'blue'), ('white', 'green'), ('black', 'red'), ('black', 'blue'), ('black', 'green')]

Build lists inside list or tuples or dict

[dict([[x, y]]) for x in list_one for y in list_two]

So here is example to find prime numbers using Trial division  more methods:

[prime for prime in range(2, n) if prime not in [notAPrime for i in range(2, int(n**0.5)) for notAPrime in range(i * 2, n, i)]]

Break it n play with it..

 Another simple way to find prime :
[prime for prime in range(2,n) if not[i for i in range(2,prime) if prime%i == 0]]

Happy python J