4

In the following code I output the range of values which I can use to index the list lst. However, due to some oddity of Python's format literals the output contains two opening and two closing parentheses instead of one. I don't see what's wrong with my format string. I just put all expressions which should be substituted in curly braces. The rest should not be substituted.

lst = [1,2,3,4,5,6]
print(f"range({-len(lst), len(lst)})")
> range((-6, 6))

2 Answers 2

5

The expression -len(lst), len(lst) is a tuple. Usually it's the comma that makes a tuple, not the parentheses. So your output shows the outer parentheses that you explicitly wrote, and the inner parentheses from the tuple. To avoid that, have a separate format for each item you want to print:

print(f"range({-len(lst)}, {len(lst)})")

Alternatively, you can remove the explicit parentheses:

print(f"range{-len(lst), len(lst)}")
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, i should have come to the conclusion on my own. Sometimes one does not see the forest for the trees.
@pqans. No worries. I strongly suspect that this Q&A will be useful to future readers :)
0

You should have put the curly brackets individually, not in whole. Like:

print(f"range({-len(lst)}, {len(lst)})")

If that doesn't work then I don't know any other solutions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.