pub-3785248829033902 | Python: List comprehensions | - Big data with Python

| Python: List comprehensions |

Python supports a concept called "list comprehensions". It can be used to construct lists in a very natural, easy way, like a mathematician is used to do.

The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics.

set = {x² : x in {0 ... 9}}
tuple = (1, 2, 4, 8, ..., 2¹²)
vector = {x | x in S and x even}



The best way to learn new things is to take a practical approach of the things you want to learn. Here is a fragment of code that demonstrates the use of the list comprehensions  statement in Python:

Æ’ python command

def fibonacci(n):
    a, b = 0, 1
    for _ in range(1, n):
        a, b = b, a + b
    return b

print([fibonacci(i) for i in range(0, 10)]

output

[1, 1, 1, 2, 3, 5, 8, 13, 21, 34]
  
Previous
Next Post »