There are two issues with the set literal syntax:
my_set = {'foo', 'bar', 'baz'}
It's not available before Python 2.7
There's no way to express an empty set using that syntax (using
{}creates an empty dict)
The section of the docs outlining this syntax is here.
Answer from bgporter on Stack OverflowThere are two issues with the set literal syntax:
my_set = {'foo', 'bar', 'baz'}
It's not available before Python 2.7
There's no way to express an empty set using that syntax (using
{}creates an empty dict)
The section of the docs outlining this syntax is here.
Compare also the difference between {} and set() with a single word argument.
>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'}
>>> b = {'aardvark'}
>>> b
{'aardvark'}
but both a and b are sets of course.
Videos
I am refreshing python skills after some time, I am getting confused when to use diff types of brackets, round, curly, or square
Any advice or tips on how to memorize or understand this?
Thanks
Square brackets: []
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'
Parentheses: () (AKA "round brackets")
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 expressions:
(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:
Curly braces: {}
Dictionaries and sets, as well as in string formatting
- Dicts:
{},{0: 10},{i: i**2 for i in range(5)} - Sets:
{0},{i**2 for i in range(5)}- Except the empty set:
set()
- Except the empty set:
- In string formatting to indicate replacement fields:
- F-strings:
f'{foobar}' - Format strings:
'{}'.format(foobar)
- F-strings:
Regular expressions
All of these brackets are also used in regex. Basically, [] are used for character classes, () for grouping, and {} for repetition. For details, see The Regular Expressions FAQ.
Angle brackets: <>
Used when representing certain objects like functions, classes, and class instances if the class doesn't override __repr__(), for example:
>>> print
<built-in function print>
>>> zip
<class 'zip'>
>>> zip()
<zip object at 0x7f95df5a7340>
(Note that these aren't proper Unicode angle brackets, like โจโฉ, but repurposed less-than and greater-than signs.)
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.