Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"can't use starred expression here"

I would like to return two things instead of a list of two elements. I could use return sorted_list[0], sorted_list[1] but I guess it would be less time-efficient. So I wanted to unpack the list directly in the return statement to time the two solutions and pick the quickest one but it doesn’t work. Here is a minimal reproducible example:

def sort_two_str(str1: str, str2: str):
    return *sorted((str1, str2))

if __name__ == "__main__":
    print(sort_two_str("A2", "A1"))

Output:

  File "path/to/file.py", line 2
    return *sorted((str1, str2))
           ^
SyntaxError: can't use starred expression here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t return two things… Also I suggest avoid thinking about these micro-optimizations.

If you return an iterable which has two items, you can then unpack it like:

a, b = func()

Interestingly if you add a single , after your expression, it becomes valid. In fact it gets turned into tuple.

def sort_two_str(str1: str, str2: str):
    return *sorted((str1, str2)),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading