Home > Articles > Open Source > Python

  • Print
  • + Share This
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
  • + Share This
  • 🔖 Save To Your Account