Why do you use parentheses sometimes and other times you don’t?
EX: figsize=(10,8) VS linewidth=2 or bins = 12
I just don’t understand the difference.
Why do you use parentheses sometimes and other times you don’t?
EX: figsize=(10,8) VS linewidth=2 or bins = 12
I just don’t understand the difference.
Parens (or sometimes called brackets in math lingo) take the highest precedence in order of operations. We normally only use them when we need to amend that order. It’s called grouping and from a syntax point of view parens may not be needed, but from a program logic standpoint they are useful.
Eg.
We often see,
(a * b) + c
in code patterns, but we also know the brackets are not needed.
a * b + c
will yield the same result. Multiplication over addition in precedence terms.
For that specific query figsize
is a default argument of a ‘function’, I’m assuming it’s matplotlib.pyplot.figure()
- https://matplotlib.org/3.3.1/api/_as_gen/matplotlib.pyplot.figure.html#matplotlib.pyplot.figure.
It takes two values namely the width
and the height
in inches. Your parentheses are in this case is creating a tuple, python’s simplest sequence type which is then the argument passed to the figsize
keyword in that function call.
So as for why some parameters have values wrapped in parantheses it’s because you can’t use commas for multiple values since they’d be treated as arguments of the function call so the ()
are necessary to create that tuple before passing its reference. Worth nosing through the description here which also covers using tuples with function calls (it’s not long)-
https://docs.python.org/3.8/library/stdtypes.html#typesseq-tuple
Thanks so much for this explanation. I’ll check out the documentation.