Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name is not defined in a list comprehension with multiple loops

I'm trying to unpack a complex dictionary and I'm getting a NameError in a list comprehension expression using multiple loops:

a={
  1: [{'n': 1}, {'n': 2}],
  2: [{'n': 3}, {'n': 4}],
  3: [{'n': 5}],
}
good = [1,2]
print [r['n'] for r in a[g] for g in good]
# NameError: name 'g' is not defined
like image 801
Iakov Davydov Avatar asked Feb 18 '16 11:02

Iakov Davydov


People also ask

Can every for loop be written as a list comprehension?

From loops to comprehensions Every list comprehension can be rewritten as a for loop but not every for loop can be rewritten as a list comprehension. The key to understanding when to use list comprehensions is to practice identifying problems that smell like list comprehensions.

How loop and list comprehensions are connected?

List comprehensions are also more declarative than loops, which means they're easier to read and understand. Loops require you to focus on how the list is created. You have to manually create an empty list, loop over the elements, and add each of them to the end of the list.

What is the difference between list comprehension and for loop?

The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code. List comprehension requires less computation power than a for loop because it takes up less space and code.


1 Answers

You have the order of your loops mixed up; they are considered nested from left to right, so for r in a[g] is the outer loop and executed first. Swap out the loops:

print [r['n'] for g in good for r in a[g]]

Now g is defined for the next loop, for r in a[g], and the expression no longer raises an exception:

>>> a={
...   1: [{'n': 1}, {'n': 2}],
...   2: [{'n': 3}, {'n': 4}],
...   3: [{'n': 5}],
... }
>>> good = [1,2]
>>> [r['n'] for g in good for r in a[g]]
[1, 2, 3, 4]
like image 75
Martijn Pieters Avatar answered Oct 12 '22 23:10

Martijn Pieters