Why must lists be followed by brackets instead of parentheses, like functions?
Lists are defined by the brackets. Function parameters and tuples are defined by the parens. Dictionaries and sets are defined by the braces.
my_list = []
Above, we define my_list
by assigning it an empty list. Now it will inherit all the list methods that are built in to Python’s standard library.
We should not confuse the list brackets with an object subscript.
my_list[0]
That references the first element of the list.
Brackets surrounding the sequence tell the Python interpreter that the data structure is a list. Brackets following a list (or string) tell the interpreter that you are trying to use an index. Brackets in the same location containing a colon tell the interpreter that you are trying to use a slice.
Parentheses surrounding something tell the interpreter “look in here and evaluate this expression first”. If the something is a sequence separated by commas, the interpreter knows that you are using a tuple. If the parentheses follow a function declaration, it knows that they surround a **sequence of parameters **. If they follow a function call, it knows that they surround a sequence of arguments.
I see, thank you for the quick reply, you two. I was thinking having everything use parentheses (or brackets, or whatever else, as long as it was one standard across all uses) would minimize chances for syntax errors, but since the language is coded to interpret their contents differently, that makes a lot of sense.
If there is a sequence separated by commas standing alone, it is a tuple.
If surrounded by parentheses, still a tuple.
If surrounded by brackets, it a list.
If surrounded by “curly braces”, it is a set.
Each of these data types has its own methods and attributes.
Wow, this is such a good explanation, thank you so much for it. Bookmarked!
Wish i had found something similar for differences in Ruby’s usage of square/curly/parens as well!
Thanks for this! This is a brilliant way of interpreting the logic behind each symbol! You and and the ‘mtf’ guy are great explainers.
surrounded by parentheses → tuple
surrounded by brackets → list
surrounded by curly braces → sets or dictionaries
#mynotes
HERE IS MY EXAMPLE about different uses of parenthesis
you can copy-paste in a Python compiler an RUN!
This is a great example andrea, and a bit of a fun fact: there can’t be any repetitions in a set; meaning if you have “banana” twice, it’ll only print it once and if the second instance was added at the end of the list, it will print at the end of the list. This example here was useful in helping me associate what goes with what, thank you!
Kind regards,
Juan
This helped me so much thank you!