Python is Awesome: List Comprehensions

in #math7 years ago

Python is Awesome!


I wrote an earlier post on lambdas and built-in functions in python.

List comprehensions are another really cool feature of python.


Let's say I have a function isPrime which tells me if a number is prime.
Let's say I want all of the prime numbers ending in "7" less than 1000.
I can do this in one line as follows:

s = [x for x in range(1000) if isPrime(x) and str(x)[-1] == "7"]

This is called a list comprehension and it's very nice as it allows you to turn this:

l = []
for i in range(100):
    if i % 2 == 0:
        l.append(2**i)

into this:

l = [2**i for i in range(100) if i % 2 == 0]

Dictionary Comprehensions!


You can also do a similar thing with dictionaries:

d = {str(i):i for i in range(100)}

is essentially this:

d = {"1": 1, "2":2, "3":3, ..., "99":99}

For more information:
http://blog.endpoint.com/2014/04/dictionary-comprehensions-in-python.html

Sort:  

Consider explaining the subject in more details, like writing an equivalent function for a list comprehension, compare performance etc. It would be also worth noting that writing this: (i for i in (1, 2, 3)) we get generator instead of tuple.

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.029
BTC 57112.10
ETH 2405.80
USDT 1.00
SBD 2.28