␡
- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
This chapter is from the book
2.14 List Comprehensions
These are just fancy terms to indicate how you can programmatically use a for loop to put together an entire list on a single line:
>>> squared = [x ** 2 for x in range(4)] >>> for i in squared: ... print i 0 1 4 9
List comprehensions can do even fancier things like being selective of what to include in the new list:
>>> sqdEvens = [x ** 2 for x in range(8) if not x % 2] >>> >>> for i in sqdEvens: ... print i 0 4 16 36