LLI Wiki — My Digital Knowledge Base

Python: list comprehensions and map to transform data

Compare loops, list comprehensions and map() with examples on strings and grids.

A list comprehension ([... for ... in ...]) or the map() function transforms every element of a sequence in a single expression. The examples below start from strings and simple grids.

ASCII codes of characters

One-line version. It produces map objects, not lists: the next form gives lists directly.

test = list([map(lambda x: ord(x), line) for line in "aaAA\nBBB".split("\n")])
[list(map(ord, line)) for line in 'aa\nbb'.splitlines()]

Result: [[97, 97], [98, 98]]

Explicit loop version

result = []
for line in 'aa\nbb'.splitlines():
    z = []
    for ch in line:
        z.append(ord(ch))
    result.append(z)

result

Result: [[97, 97], [98, 98]]

Comprehension version:

[ [ ord(x) for x in line ] for line in 'aa\nbb'.splitlines() ]
grille = ['O', 'O', 'O', 'O'],['X', 'X', 'X', 'X ']
print('\n'.join(''.join(s) for s in grille))
grille = ['O', 'O', 'O', 'O'],['X', 'X', 'X', 'X ']
print('\n'.join(map(''.join, grille)))

Same result with an explicit loop:

def display(g):
    for line in g:
        s = ''
        for symbol in line:
            s += symbol
        print(s)

display(grille)

Dictionary comprehension

g = { (x, y): (x+y) for x in range(3) for y in range(3) }
[ [ g[x, y] for x in range(3) ] for y in range(3) ]

Result: [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

Mastodon LLIMastodon SocialFosstodon