J K
J K

Reputation: 165

NameError: name 'x' is not defined (x declared in for loop)

I'm getting below error for below mentioned code:

NameError: name 'x' is not defined

list_keywords=['DROP','CREATE','ALTER','COMMENT']
file=open(filename)
for line in file:
    if any(x in line.upper() for x in list_keywords):
        print (x)

I'm able to print the line containing any of the strings mentioned in the list.

Below code works.

list_keywords=['DROP','CREATE','ALTER','COMMENT']
file=open(filename)
for line in file:
    if any(x in line.upper() for x in list_keywords):
        print (line)

Could someone please let me know why print(x) does not work?

Upvotes: 1

Views: 1240

Answers (3)

quamrana
quamrana

Reputation: 39354

I'm not sure what you want, but this might give you the information you are looking for:

list_keywords=['DROP','CREATE','ALTER','COMMENT']
file=open(filename)
for line in file:
    results = [(line,x) for x in list_keywords if x in line.upper()]
    if results:
        print(results)

I tested with this code:

list_keywords=['DROP','CREATE','ALTER','COMMENT']
file=['foo','bar','drop comment','zoo']
for line in file:
    results = [(line,x) for x in list_keywords if x in line.upper()]
    if results:
        print(results)

Output:

[('drop comment', 'DROP'), ('drop comment', 'COMMENT')]

Upvotes: 1

Chris_Rands
Chris_Rands

Reputation: 41168

In Python 2, x is leaked into the namespace in a list comprehension (although not in a generator expression), but not in Python 3:

Py 2:

>>> [x for x in range(3)]
[0, 1, 2]
>>> x
2

Py 3:

>>> [x for x in range(3)]
[0, 1, 2]
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Anyway, if you want to get the first value that satisfies the condition then use next() instead and for all the values use a list comprhension, e.g.

>>> next(x for x in range(5) if x % 2 == 1)
1
>>> [x for x in range(5) if x % 2 == 1]
[1, 3]

Upvotes: 6

user1781434
user1781434

Reputation:

any(x in line.upper() for x in list_keywords)

The argument to any is a generator, and x is only defined within the generator.

Upvotes: 1

Related Questions