Nested list comprehensions, unlike list comprehensions with nested loops, are List comprehensions within a list

comprehension. The initial expression can be any arbitrary expression, including another list comprehension.

*#List Comprehension with nested loop*

[x + y **for** x **in** [1, 2, 3] **for** y **in** [3, 4, 5]]

*#Out: [4, 5, 6, 5, 6, 7, 6, 7, 8]*

*#Nested List Comprehension*

[[x + y **for** x **in** [1, 2, 3]] **for** y **in** [3, 4, 5]]

*#Out: [[4, 5, 6], [5, 6, 7], [6, 7, 8]]*

The Nested example is equivalent to

l = []

**for** y **in** [3, 4, 5]:

temp = []

**for** x **in** [1, 2, 3]:

temp.append(x + y)

l.append(temp)

One example where a nested comprehension can be used it to transpose a matrix.

matrix = [[1,2,3],

[4,5,6],

[7,8,9]]

[[row[i] **for** row **in** matrix] **for** i **in** range(len(matrix))]

*# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]*

Like nested **for** loops, there is no limit to how deep comprehensions can be nested.

[[[i + j + k **for** k **in** 'cd'] **for** j **in** 'ab'] **for** i **in** '12']

*# Out: [[['1ac', '1ad'], ['1bc', '1bd']], [['2ac', '2ad'], ['2bc', '2bd']]]*

Understanding Nonlocal Variables in Python: A Beginner GuideChapter 13: Variable Scope and Binding Section 13.1: Nonlocal Variables Python 3.x Version ≥ 3.0 Python 3 added a new keyword called nonlocal. The nonlocal keyword adds a scope override to the inner scope. You can read all about it in PEP 3104. This is best illustrated with a couple of code examples. One of […]