Reputation: 183
I am trying to extract the index of an element in a list that says the word "FAILED".
In my application, I am looking to extract the specific element because I want to apply some regular expression to get some info regarding the FAILED status.
test_list = ["This is a test element", "This is a FAILED test element"]
if any("FAILED" for x in test_list):
failed = x
end_line = test_list.index(failed)
else:
end_line = test_list[-1]
print(end_line)
I want x to == test_list[1] or x == 1.. In my application, I won't know the index of where "FAILED" will occur.
This is the error: NameError: name 'x' is not defined
Upvotes: 1
Views: 53
Reputation: 1828
Try this:
test_list = ["This is a test element", "This is a FAILED test element", "x", "y"]
for i, x in enumerate(test_list):
if "FAILED" in x:
end_line = test_list[i]
break
else:
end_line = test_list[-1]
print(end_line)
Output
This is a FAILED test element
Upvotes: 1
Reputation: 18519
You're getting such error since the scope of x
is limited to the generator in which it is used -- namely the one you're passing to any(...)
.
You could go with something like this:
test_list = ["This is a test element", "This is a FAILED test element"]
end_idx = -1
for i, x in enumerate(test_list):
if "FAILED" in x:
failed = x
end_idx = i
end_line = test_list[end_idx]
With this you also avoid making another access to the list to get the index of failed
with .index(...)
Upvotes: 1
Reputation: 943
variable x loses it's scope once it exists
any("FAILED" for x in test_list)
you can do,
temp = ""
for x in test_list:
if "FAILED" in x:
failed = x
end_line = test_list.index(failed)
break
.... #your code..
Upvotes: 1
Reputation: 5502
You can use list-comprehension. The following code shows all the index where the substring FAILED
is present.
Code:
test_list = ["This is a test element", "This is a FAILED test element"]
output = [i for i, string in enumerate(test_list) if 'FAILED' in string]
print(output)
# [1]
Upvotes: 1