Python: list, tuple, list comprehension and generator
November 15, 2009 21:44:23
Python lists are enclosed in square brackets. When a list of objects are enclosed in parentheses it is a tuple (an immutable list). List comprehensions are enclosed in square brackets. But when you change the square brackets to parentheses, you get a generator not a tuple!
>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> t = (1, 2, 3, 4, 5, 6, 7, 8, 9) >>> type(l) <type 'list'> >>> type(t) <type 'tuple'> >>> l2 = [i for i in l if i % 2 != 0] >>> l2 [1, 3, 5, 7, 9] >>> g1 = (i for i in l if i % 2 != 0) >>> type(g1) <type 'generator'> >>> g2 = (i for i in t if i % 2 != 0) >>> type(g2) <type 'generator'> >>> g1 == g2 False >>> sum(g2) 25 >>> sum(g1) 25
Easy email testing with http://www.ximailstop.com