Skip to Content
Pandas for Everyone: Python Data Analysis, First Edition
book

Pandas for Everyone: Python Data Analysis, First Edition

by Daniel Y. Chen
December 2017
Beginner to intermediate
410 pages
12h 45m
English
Addison-Wesley Professional
Content preview from Pandas for Everyone: Python Data Analysis, First Edition

N. Comprehensions

A typical task in Python is to iterate over a list, run some function on each value, and save the results into a new list.

# create a list l = [1, 2, 3, 4, 5] # list of newly calculated results r = [] # iterate over the list for i in l:     # square each number and add the new value to a new list     r.append(i ** 2) print(r)

[1, 4, 9, 16, 25]

Unfortunately, this approach requires a few lines of code to do a relatively simple task. One way to rewrite this loop more compactly is by using a Python list-comprehension. This shortcut offers a concise way of performing the same action.

# note the square brackets around on the right-hand side # this saves the final results ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Pandas for Everyone: Python Data Analysis, 2nd Edition

Pandas for Everyone: Python Data Analysis, 2nd Edition

Daniel Y. Chen

Publisher Resources

ISBN: 9780134547046Purchase book