# Normal use of a for loop ...## without list comprehension
str = "abc"
res = []
for s in str:
res.append(s.capitalize())
assert res == ['A', 'B', 'C']
Comprehension
For loops can be write more concisely using list comprehension.
# List comprehension## The loop variable appears in expression before we get to definition# List comprehensions are more concise but are harder to debug
str = "abc"
res = [s.capitalize() for s in str]
assert res == ['A', 'B', 'C']
Application
List comprehension in action, convert matrix to tree.
""" Matrix to Tree
"""
matrix = [
[3, 4],
[8, [-2, 10], 5],
7,
]
classNode:def__init__(self, value=None, children=[]):
self.value = value
self.children = children
defmatrix_to_tree(m):# with For loopif isinstance(m, int):
return Node(m, [])
children = []
for child in m:
sub_node = matrix_to_tree(child)
children.append(sub_node)
return Node(None, children)
tree = matrix_to_tree(matrix)
assert tree.children[0].children[0].value == 3assert tree.children[0].children[1].value == 4assert tree.children[1].children[0].value == 8assert tree.children[1].children[1].children[0].value == -2assert tree.children[1].children[1].children[1].value == 10assert tree.children[2].value == 7defmatrix_to_tree(m):# with List comprehensionif isinstance(m, int):
return Node(m, [])
children = [matrix_to_tree(x) for x in m] # Look Herereturn Node(None, children)
tree = matrix_to_tree(matrix)
assert tree.children[0].children[0].value == 3assert tree.children[0].children[1].value == 4assert tree.children[1].children[0].value == 8assert tree.children[1].children[1].children[0].value == -2assert tree.children[1].children[1].children[1].value == 10assert tree.children[2].value == 7