Comprehensions

Python for R Users

Daniel Chen

Instructor

Comprehensions are loops

  • Iterate (loop) through a list
  • Perform some function
  • Append results into a new list
Python for R Users

List comprehension

Loop
data = [1, 2, 3, 4, 5]
new = []
for x in data:
    new.append(x**2)
print(new)
[1, 4, 9, 16, 25]
Comprehension
data = [1, 2, 3, 4, 5]

new = [x**2 for x in data]
print(new)
[1, 4, 9, 16, 25]
Python for R Users

Dictionary comprehension

Loop
data = [1, 2, 3, 4, 5]
new = {}

for x in data:
    new[x] = x**2
print(new)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Comprehension
data = [1, 2, 3, 4, 5]

new = {x: x**2 for x in data}
print(new)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Python for R Users

Alternatives to `for` loop

  • for loop to iterate
  • R: sapply, lapply, apply functions
  • Python: map function and apply method
Python for R Users

Map

For Loop
def sq(x):
    return x**2

l = [1, 2, 3]
for i in l:
    print(sq(i))
1
4
9
Map
map(sq, l)
<map at 0x7f41cca38358>
list(map(sq, l))
[1, 4, 9]
Python for R Users

Let's practice!

Python for R Users

Preparing Video For Download...