List Iteration and Comprehensions
print( 3 in [1, 2, 3] ) # Membership for x in [1, 2, 3]: print(x, end=' ') # Iteration (2.X uses: print x,) # www . j av a2 s. c o m
for loops step through items in any sequence from left to right, executing one or more statements for each item.
List comprehensions build a new list by applying an expression to each item in a sequence:
res = [c * 4 for c in 'TEST'] # List comprehensions print( res )
This expression is functionally equivalent to a for loop that builds up a list of results manually:
res = [] for c in 'TEST': # List comprehension equivalent res.append(c * 4) # w ww . java2s .c o m print( res )
The map built-in function applies a function to items in a sequence and collects all the results in a new list:
print( list(map(abs, [-1, -2, 0, 1, 2])) ) # Map a function across a sequence