I'm trying to generate a list of strings using a list comprehension, where the string is formatted using f-strings:
features = [("month", (1, 12)), ("day_of_year", (1, 365))]
for feature, range in features:
cols= [f"transformed_{feature}_period_{i:02d}" for i in range(12)]
If I run this code, I get an error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 3
1 features = [("month", (1, 12)), ("day_of_year", (1, 365))]
2 for feature, range in features:
----> 3 cols= [f"transformed_{feature}_period_{i:02d}" for i in range(12)]
TypeError: 'tuple' object is not callable
I still get the error even if I remove the variables from the string:
for feature, range in features:
cols= ["transformed_feature_period" for i in range(12)]
I don't understand why the interpreter is complaining that I'm trying to call a tuple. I'm able to perform other operations, such as actual function calling and asserts inside the outer for loop, but I keep bumping into this error when trying to use a list comprehension.
Thanks in advance for any help.
If you don't actually use the range,
for feature, _ in features:
...
If you only care about the endpoints of the range,
for feature, (start, stop) in features:
...
If you really need a reference to the tuple as a whole, pick a name that doesn't shadow the built-in type you use later:
for feature, feature_range in features:
...
I don't recommend using builtins.range
to access the shadowed type when it's simpler to provide a more accurate name for the index variable in the first place.