List Comprehension, or How I learned to Stop Worrying and Love the List 
Published: 2019-09-28 19:27:15

---
title: List Comprehension, or How I learned to Stop Worrying and Love the List 
published: true
description: 
tags: 
---


Lists and Dictionaries are a powerful part of the Python toolbox. They are useful in any language, but Python has some new twists that make them even more versatile and easier to use. Many languages differ on how they create a List, and whether or not it can be populated upon instantiation. Some languages, like Java, require that a List be created empty and then populated afterwards. Python, however, allows us the luxury of creating a pre-populated list. All we have to do is write out the items in a list format:

```python
alpha = [‘a’,’b’,’c’]
```

###Lists and Loops

But say we want to create a much longer List, or a List based on a more complex pattern? For instance, what if we want all even numbers from 0 to 60? We could just write out every number, but that would take a long time and look very messy. In some languages the solution to this would be a loop, and add the next number in the sequence each iteration. Here’s how that would look:

```python
evens = []

for i in range(0,61,2):
	evens.append(i)
```

###List Comprehension

This is fine for this level of complexity, but Python has shortcuts to simplify these kind of operations. List Comprehension operates a bit like a simplified for-loop, and outputs a new list where each iteration of the loop outputs another item in the output List. For example, the List Comprehension version of the above code would be:

```python
evens = [i for i in range(0,61,2)]
```  

The basic syntax for this kind of statement is written as [*expression* for *item* in *list*], where the *list* is an input List, the *item* is each individual item from that list, and the *expression* is how you’re transforming the item. For instance if we wanted every even number multiplied by 3, we would write it as:

 ```python
evens = [I*3 for i in range(0,61,2)]
```  

###Conditionals in List Comprehension

But let’s say we want to get more complex, what if we want to use an if-statement, does that mean we need to go back to a for-loop? Well, let’s start with the for loop again. This time, we’re going to take an input list of numbers, and output 1 for positive numbers, 0 for negative:

```python
input = [1,-2,56,30,-23,-4,52]
output = []

for i in input:
	if i >= 0:
		output.append(1)
	else:
		output.append(0)
```

Now we’re getting several layers of indentation here. So how do we put this into List Comprehension? To start with, let’s talk about inline if-statements. In addition to writing if-statements in the traditional format, Python also allows in-line if-statements, which are written in a single line. While not always appropriate, in-line statements are handy for using with List Comprehension. For example:

```python
#this statement:

if i >= 0:
		output.append(1)
	else:
		output.append(0)

#can be re-written as:

output.append(1) if i >= 0 else output.append(0) 

```

And so the inline statement is written as *expression* if *condition* else *2nd expression*. But how does this help us? Now that we can write an if-statement in a single line, we can incorporate it into a List Comprehension. If we want to re-write the previous loop, we now have a way to do that:

```python
output = [1 if i >= 0 else 0 for i in input] 
```

Notice how we have simply placed the inline statement into the expression part of the List Comprehension, and now it directly returns a list of the correct format. In this example I have used an if-else statement, but when using an if statement with no *else* expression, the structure is slightly different. An if by itself should be written at the end instead, like so:

```python
output = [1 for i in input if i >= 0]
```

###Dictionary Comprehension

Now we can create new lists with complex conditions in a single line, and simplify our code. In addition to List Comprehension there is something else allowed in Python 2.7+: Dictionary Comprehension. Similar to List Comprehension, Dictionary Comprehension allows you to create a Dictionary in single line based on another collection and using inline statements. For instance, you could create a dictionary with a set of keys, all with an initial value of True:

```python
output_dict = {k : True for k in input}
```

Comprehensions can be very useful and very powerful tools in Python development, and I hope this helps you better understand how comprehensions work, and how they can be useful.