Search code examples
pythonlistlist-comprehension

Python list comprehension: Unlist if list contains only one element


I have got the following function:

output_names = [output.name for output in session.get_outputs()]

session.get_outputs() can return multiple multiple objects which I want to get the name property from. If the length of the list is 1, I want to output_names to be a value, not a list with a single value.

output_names = [output.name for output in session.get_outputs()]
if len(output_names) == 1:
    output_names = output_names[0]

I could do it like this, but this feels like a code smell. It there a more elegant way to solve this?


Solution

  • How about adjusting the way you construct output_names like:

    outputs = session.get_outputs()
    output_names = [output.name for output in outputs] if len(outputs)>1 else outputs.name
    

    That said, mixing data types is not desirable, imo.