I've been loving the tuple comprehensions added to Python3.5:
In [128]: *(x for x in range(5)),
Out[128]: (0, 1, 2, 3, 4)
However, when I try to return
a tuple comprehension directly I get an error:
In [133]: def testFunc():
...: return *(x for x in range(5)),
...:
File "<ipython-input-133-e6dd0ba638b7>", line 2
return *(x for x in range(5)),
^
SyntaxError: invalid syntax
This is just a slight inconvenience since I can simply assign the tuple comprehension to a variable and return the variable. However, if I try and put a tuple comprehension inside a dictionary comprehension I get the same error:
In [130]: {idx: *(x for x in range(5)), for idx in range(5)}
File "<ipython-input-130-3e9a3eee879c>", line 1
{idx: *(x for x in range(5)), for idx in range(5)}
^
SyntaxError: invalid syntax
I feel like this is a bit more of a problem since comprehsions can be important for performance in some situations.
I have no problem using dictionary and list comprehensions in these situations. How many other situations is the tuple comprehension not going to work when others do? Or perhaps I'm using it wrong?
It makes me wonder what the point was if it's use is so limited or perhaps I am doing something wrong? If I'm not doing something wrong then what is the fastest/most pythonic way to create a tuple that is versitile enough to be used in the same way as list and dictionary comprehensions?