> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/prog/python/list-comprehensions.md).

# List comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

## Examples of List Comprehensions

### List of Squares

To create a list of [square numbers](https://en.wikipedia.org/wiki/Square_\(algebra\))

```python
squares = [x**2 for x in range(10)]
```

The result is the following:

```python
>>> print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
```

### List of Even Numbers

To create a list of even numbers

```python
even_numbers = [num for num in range(1, 10) if num % 2 == 0 ]
```

The result is the following:

```python
>>> print(even_numbers)
[2, 4, 6, 8]
```

### List of Pronic Numbers

To create a list of [pronic numbers](https://en.wikipedia.org/wiki/Pronic_number)

```python
def pronic(n):
    return n * (n+1)
    
port_list = [pronic(n) for n in range(5, 15)]
```

The result is the following:

```python
>>> print(port_list)
[30, 42, 56, 72, 90, 110, 132, 156, 182, 210]
```

## Resources

List Comprehensions - Python: <https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions>
