Python - Data Type List Comprehensions

Introduction

A list comprehension expression is a powerful way to process structures like our matrix.

To extract the second column of our sample matrix, grab rows by simple indexing because the matrix is stored by rows comprehension:

Demo

M = [[1, 2, 3],               # A 3 ? 3 matrix, as nested lists 
     [4, 5, 6],               # Code can span lines if bracketed 
     [7, 8, 9]] #  www .  ja  v a2s.com

col2 = [row[1] for row in M]  # Collect the items in column 2 
print( col2 )
print( M )                    # The matrix is unchanged

Result

List comprehensions derive from set notation.

They build a new list by running an expression on each item in a sequence, one at a time, from left to right.

List comprehensions are coded in square brackets and are composed of an expression and a looping construct that share a variable name (row, here).

The preceding list comprehension means: "Give me row[1] for each row in matrix M, in a new list."

The result is a new list containing column 2 of the matrix.

More Example

Demo

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

print( [row[1] + 1 for row in M] )                 # Add 1 to each item in column 2 
print( [row[1] for row in M if row[1] % 2 == 0] )  # Filter out odd items

Result

The first operation here adds 1 to each item as it is collected.

The second uses an if clause to filter odd numbers out of the result using the % modulus expression (remainder of division).

List comprehensions make new lists of results, but they can iterate over any iterable object.

Here, for instance, we use list comprehensions to step over a hardcoded list of coordinates and a string:

Demo

M = [[1, 2, 3],               # A 3 ? 3 matrix, as nested lists 
     [4, 5, 6],               # Code can span lines if bracketed 
     [7, 8, 9]] #  w  w w .  j av  a2s.  c om
diag = [M[i][i] for i in [0, 1, 2]]      # Collect a diagonal from matrix 
print( diag )

doubles = [c * 2 for c in 'test']        # Repeat characters in a string 
print( doubles )

Result

These expressions can collect multiple values, as long as we wrap those values in a nested collection.

Related Topic