Python - List Iteration and Comprehensions

Description

List Iteration and Comprehensions

Demo

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

Result

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:

Demo

res = [c * 4 for c in 'TEST']            # List comprehensions 
print( res )

Result

This expression is functionally equivalent to a for loop that builds up a list of results manually:

Demo

res = [] 
for c in 'TEST':                         # List comprehension equivalent 
    res.append(c * 4) # w  ww . java2s .c  o  m
print( res )

Result

The map built-in function applies a function to items in a sequence and collects all the results in a new list:

Demo

print( list(map(abs, [-1, -2, 0, 1, 2])) )        # Map a function across a sequence

Result

Related Topics

Example