Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/02-Python Statements/06-List Comprehensions.ipynb
Views: 648
List Comprehensions
In addition to sequence operations and list methods, Python includes a more advanced operation called a list comprehension.
List comprehensions allow us to build out lists using a different notation. You can think of it as essentially a one line for
loop built inside of brackets. For a simple example:
Example 1
This is the basic idea of a list comprehension. If you're familiar with mathematical notation this format should feel familiar for example: x^2 : x in { 0,1,2...10 }
Let's see a few more examples of list comprehensions in Python:
Example 2
Example 3
Let's see how to add in if
statements:
Example 4
Can also do more complicated arithmetic:
Example 5
We can also perform nested list comprehensions, for example:
Later on in the course we will learn about generator comprehensions. After this lecture you should feel comfortable reading and writing basic list comprehensions.