MiniMe MiniMe - 5 months ago 8
Python Question

What is an elegant way to convert the result of [x for x in y] from list to a regular variable?

What is an elegant way to convert the result of

[x for x in y]
from list to a regular variable?

result= [x for x in range(10) if x==7]


The result of the above will be
[7]
.
I am now using
result=result[0]
but ...it does not look right :-)

thanks

Answer

You have a list comprehension on the right hand side. It evaluates to a list.

You want to pick up the first element (which is perhaps the only element for the kind of problems you are trying to solve) from it, so index the 0-th element in the list returned by the list comprehension, just like you would do it for a regular list.

result = [x for x in range(10) if x == 7][0]

You can also use a generator expression instead of a list expression and then call the next() function to retrieve the first item from the iterator returned by the generator expression.

result = next(x for x in range(10) if x == 7)
Comments