'"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
Solution 1:[1]
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)),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | S.B |
