Python by Swaroop C H - HTML preview
PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.
Download the book in PDF, ePub, Kindle for a complete version.
Using List Comprehensions
Example 15.1. Using List Comprehensions
#!/usr/bin/python# Filename: list_comprehension.py
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2] print listtwo
Output
$ python list_comprehension.py [6, 8]How It Works
Here, we derive a new list by specifying the manipulation to be done ( 2*i) when some condition is satisfied (if i > 2). Note that the original list remains unmodified. Many a time, we use loops to process each element of a list, the same can be achieved using list comprehensions in a more precise, compact and explicit manner.
