-
Notifications
You must be signed in to change notification settings - Fork 13
/
list_comprehensions.Rmd
56 lines (45 loc) · 1.71 KB
/
list_comprehensions.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
---
jupyter:
orphan: true
jupytext:
text_representation:
extension: .Rmd
format_name: rmarkdown
format_version: '1.2'
jupytext_version: 1.11.5
kernelspec:
display_name: Python 3 (ipykernel)
language: python
name: python3
---
# List comprehensions
List comprehensions are a nice short-cut for simple `for` loops in Python.
The list comprehension is a single expression that returns a list, element by
element.
Let’s say you wanted to create a list of values for squared numbers. You might
do it like this:
```{python}
squared_numbers = []
for i in range(10): # numbers 0 through 9
squared_numbers.append(i ** 2)
squared_numbers
```
It turns out this kind of thing is a very common pattern in Python. The
pattern is: create an empty list, then use a for loop to fill in values for
the list.
List comprehensions are a short cut for that pattern:
```{python}
squared_numbers = [i ** 2 for i in range(10)]
squared_numbers
```
The list comprehesion is an *expression*, starting and ending with square
brackets. The first thing inside the square brackets is the expression that
will become the element of the list - in this case `i \*\* 2` – followed by
a `for` clause - in this case `for in in range(10)` – that will feed
the first expression with values to use.
See the [Python docs on list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)
for more detail.
List comprehensions can be a little hard to read when you are not used to
them. If you find them confusing, as most of us do at first, then unpack them
into the equivalent `for` loop. Over time, as you get used to them, they can
be easier to read than the longer `for` loop equivalent.