Different Meanings Of Brackets In Python
I am curious, what do the 3 different brackets mean in Python programming? Not sure if I'm correct about this, but please correct me if I'm wrong: [] - Normally used for dictionar
Solution 1:
[]: Lists and indexing/lookup/slicing
- Lists:
[],[1, 2, 3],[i**2 for i in range(5)] - Indexing:
'abc'[0]→'a' - Lookup:
{0: 10}[0]→10 - Slicing:
'abc'[:2]→'ab'
(): Tuples, order of operations, generator expressions, function calls and other syntax.
- Tuples:
(),(1, 2, 3)- Although tuples can be created without parentheses:
t = 1, 2→(1, 2)
- Although tuples can be created without parentheses:
- Order of operations:
(n-1)**2 - Generator expression:
(i**2 for i in range(5)) - Function or method calls:
print(),int(),range(5),'1 2'.split(' ')- with a generator expression:
sum(i**2 for i in range(5))
- with a generator expression:
{}: Dictionaries and sets
- Dicts:
{},{0: 10},{i: i**2 for i in range(5)} - Sets:
{0},{i**2 for i in range(5)}
Solution 2:
() parentheses are used for order of operations, or order of evaluation, and are referred to as tuples. [] brackets are used for lists. List contents can be changed, unlike tuple content. {} are used to define a dictionary in a "list" called a literal.
Solution 3:
In addition to Maltysen's answer and for future readers: you can define the () and [] operators in a class, by defining the methods:
__call__(self[, args...])for()__getitem__(self, key)for[]
An example is numpy.mgrid[...]. In this way you can define it on your custom-made objects for any purpose you like.
Post a Comment for "Different Meanings Of Brackets In Python"