12. Python basics: List comprehensions – one line loops

List comprehensions are a very Pythonic way of condensing loops and action into a single line.

Here is the long form of a loop:

my_list=[1,4,5,7,9,10,3,2,16]

my_new_list=[]

for x in my_list:

    if x>5:

        my_new_list.append(x**2)

print (my_new_list)

OUT:

[49, 81, 100, 256]

This may be done by a single line list comprehension:

y = [x**2 for x in my_list if x>5]

print (y)

OUT:

[49, 81, 100, 256]

 

One thought on “12. Python basics: List comprehensions – one line loops

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s