Python - Enclosing a List comprehension in parentheses to create generators.

Introduction

To illustrate, the sum built-in sums items in a sequence:summing all items in our matrix's rows on request:

Demo

M = [[1, 2, 3],               # A 3 ? 3 matrix, as nested lists 
     [4, 5, 6],               # Code can span lines if bracketed 
     [7, 8, 9]] # from  w ww .  j  av a2 s  .  c  o  m

G = (sum(row) for row in M)              # Create a generator of row sums 
print( next(G) )                                  # iter(G) not required here 
print( next(G) )                                  # Run the iteration protocol next() 
print( next(G) )

Result

The map built-in can generate the results of running items through a function, one at a time and on request.

Demo

M = [[1, 2, 3],               # A 3 ? 3 matrix, as nested lists 
     [4, 5, 6],               # Code can span lines if bracketed 
     [7, 8, 9]] # from  w w w .j a va2 s.co m

print( list(map(sum, M)) )                        # Map sum over items in M

Result

Comprehension syntax can also be used to create sets and dictionaries:

Demo

M = [[1, 2, 3],               # A 3 ? 3 matrix, as nested lists 
     [4, 5, 6],               # Code can span lines if bracketed 
     [7, 8, 9]] # from w ww.  j a  v a 2 s  .  com

print( {sum(row) for row in M} )                  # Create a set of row sums 

print( {i : sum(M[i]) for i in range(3)} )        # Creates key/value table of row sums

Result

Lists, sets, dictionaries, and generators can all be built with comprehensions:

Demo

print( [ord(x) for x in 'test'] )               # List of character ordinals 
print( {ord(x) for x in 'test'} )                # Sets remove duplicates 
print( {x: ord(x) for x in 'test'} )             # Dictionary keys are unique 
print( (ord(x) for x in 'test') )                # Generator of values
# from  w w  w.ja v  a  2 s  . c  o m

Result

Related Topic