Introduction To List Comprehensions And Reading Lines From File Into A List
List comprehensions is an exciting feature of Python. You can build entire lists using one statement. Say, I want a list of all squares of numbers between 1 to 10, or I want a list of numbers x to the power of some y, or I have to find only even squares, then I do this:
Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [x**2 for x in range(1,10)] [1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [x**y for x in range(1,5) for y in range(1,3)] [1, 1, 2, 4, 3, 9, 4, 16] >>> [x**2 for x in range(1,10) if x%2 == 0] [4, 16, 36, 64] >>> [x**y for x in range(1,5) for y in range(1,4) if not x==y] [1, 1, 2, 8, 3, 9, 4, 16, 64] >>>
And here's how you can read lines from a file into a list using list comprehension:
import sys lines = [line.strip() for line in open("".join(sys.argv[1]),"r")] for line in lines: print line






