Why do lists use brackets instead of parenthesis?

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.

12 Likes

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.

13 Likes

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.

1 Like

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.

15 Likes

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!

1 Like

Thanks for this! This is a brilliant way of interpreting the logic behind each symbol! You and and the ‘mtf’ guy are great explainers.

1 Like