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]
                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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With