**Linear Algebra**

# Python | List Comprehension

*schedule*Mar 5, 2023

*toc*Table of Contents

*expand_more*

**interactive map of data science**

List comprehension in Python allows us to create a new list based on the values of an existing list in a short, efficient manner.

# Syntax

## Basic

```
[output expression for variable in iterable]
```

## Conditional

```
[output expression + conditional on output for variable in iterable + conditional on iterable]
```

# Examples

## Basic

If we have an existing list of numbers called `nums`

:

```
nums = [5, 9, 30, 22, 13]
```

And we want to create a new list with values one greater than the current values in `nums`

.

Using list comprehension this can be achieved using the below:

```
new_nums = [num + 1 for num in nums]print(new_nums)
[6, 10, 31, 23, 14]
```

Without using list comprehension this would look a lot longer:

```
```

## Nested

We can also leverage list comprehension to produce nested loops:

```
num_pairs = [(num1, num2) for num1 in [0,1] for num2 in [4,5]]print(num_pairs)
[(0, 4), (0, 5), (1, 4), (1, 5)]
```

## Conditional

To specify condition on output:

```
[0, 0, 0, 3, 0, 0, 6, 0, 0, 9]
```

Here for each number from 0 - 9 (specified by `range(10)`

), we add the number to the list if it is perfectly divisible by 3, or we add 0 to the list if the number is not perfectly divisible by 3.

To specify condition on input:

```
[0, 3, 6, 9]
```

Here for each number from 0-9 (specified by `range(10)`

), we first check whether the number is perfectly divisible by 3. If it is we add that number to the returned list, if not we do not add anything and simply move to check the next number in the iterable.

To specify condition on both input and output:

```
[10, 0, 16, 0]
```

Finally, here we first specify a condition on the input `if num % 3 ==0`

. If the number is perfectly divisible by 3, we then check whether the number is divisible by 2, and if so we add the number + 10 to the list, or 0 otherwise.