*This is an extension of my blog article about list comprehensions and the first part of an advanced python series. We will cover List Comprehensions, Lambdas, Functional Programming, Map / Reduce / Filter, Decorators, and Descriptors.*

# Python List Comprehensions

List comprehensions are Python's solution to the large loops required to do tasks which should be easy. They transform the simple task of getting all the even numbers between zero and one-thousand from:```
my_list = []
for index in range(1000):
if index % 2 == 0:
my_list.append(index)
```

to
```
my_list = [x for x in range(1000) if x % 2 == 0]
```

## The use for list comprehensions

List comprehensions are essentially:```
list_name = [expression values filter]
```

Values - A *for*loop of values to check against the filter Filter - All values go through this. It is an

*if*statement, and the expression is appended to the end of the list when it is true. Expression - Data to append onto the list if Filter is true It's important to note here that the expression could be anything. We could get the squares of all even numbers between zero and one-thousand just as easily:

```
my_list = [x**2 for x in range(1000) if x % 2 == 0]
```

## Interesting Points

List comprehensions work on strings, and the*for*loop can loop through any list. The expression can be as complex as you want. The expression is what gets appended, and it can even be another list. Look at this piece of code:

```
my_list = [[x*y for y in range(1,11) if y % 2 == 0] for x in range(1,11) if x % 2 == 0]
```

This generates a list of lists (which is stored in *my_list*) where every even number between one and ten is multiplied by every other even number between one and ten.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account## Sign in

Already have an account? Sign in here.

Sign In Now