Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

List Comprehensions

Many operations involving map() and filter() can be replaced with a list-construction operator known as a list comprehension. The syntax for a list comprehension is as follows:

						[expression for item1 in iterable1
            for item2 in iterable2
            ...
            for itemN in iterableN
            if condition ]

This syntax is roughly equivalent to the following code:

						
s = []
for item1 in iterable1:
    for item2 in iterable2:
        ...
           for itemN in iterableN:
               if condition: s.append(expression)

To illustrate, consider the following example:

 a = [-3,5,2,-10,7,8] b = 'abc' c = [2*s for s in a] # c = [-6,10,4,-20,14,16] d = [s for s in a if s >= 0] # d = [5,2,7,8] e = [(x,y) for x in a # e = [(5,'a'),(5,'b'),(5,'c'), for y in b # (2,'a'),(2,'b'),(2,'c'), if x > 0 ] # ...
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

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book