Python: how to reuse list views after they are created in an expression

How can I reuse the same list in an expression that is created using list comprehension with an if else expression? Reaching it in one expression / expression (without using any intermediate variable) i.e. index = 0 if [listcomprehension]is empty else, get the first element of understanding the list without having to recreate it.

carIndex = [index
            for index, name in enumerate([car.name for car in cars]) 
            if "VW" in name or "Poodle" in name][0]
+4
source share
3 answers

Use a generator expression and then with a default value of 0 if you are not going to store a list creating it is pointless:

carIndex = next((index for index, name in enumerate(car.name for car in 
cars if "VW" in car.name or "Poodle" in car.name)),-1)

0, , , , . , :

carIndex = next((index for index, car in enumerate(cars) 
if any(x in car.name for x in ("VW","Poodles"))), -1)

:

carIndex = next((0 for _ in (car for car in 
cars if "VW" in car.name or "Poodle" in car.name)),-1)

:

carIndex = 0 if any("VW" in car.name or "Poodle" in car.name for car in cars) else -1
+7

, - :

tmp =  [index
        for index, name in enumerate([car.name for car in cars]) 
        if "VW" in car.name or "Poodle" in car.name]
carIndex = [0] if len(tmp)==0 else tmp

, , , .

+1

There are several ways to do this if you REALLY don't want to use a temporary variable, but it's a bit non-python.

Here is one using lambda:

carIndex = (lambda x: 0 if not len(x) else x[1])(insert_list_comprehension_here)

EDIT: One pythonic way is to use try-except.

try:
    carIndex = [my_list_comprehension][1]
except IndexError:
    carIndex = 0
+1
source

All Articles