Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to re-use list comprehensions after they are created in an expression

How could I reuse the same list in an expression which is created using a list comprehension with an if else expression? Achieving it in a single statement/expression (without using any intermediate variable) i.e. index = 0 if [listcomprehension] is empty else get first element of the list comprehension without re-creating it

carIndex = [index
            for index, name in enumerate([car.name for car in cars]) 
            if "VW" in name or "Poodle" in name][0]
like image 647
Har Avatar asked Jan 09 '23 00:01

Har


1 Answers

Use a generator expression and next with a default value of 0, if you are not going to store the list creating one 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)

Your original logic will always return 0 if there is a match so I am not sure if that is what you want. This will actually return the index of the car that matches the name in cars:

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

You first example is equivalent to:

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

Which would simply become:

carIndex = 0 if any("VW" in car.name or "Poodle" in car.name for car in cars) else -1
like image 127
Padraic Cunningham Avatar answered Jan 16 '23 20:01

Padraic Cunningham