Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 dictionaries, list items
  • () - Used to identify params
  • {} - I have no idea what this does...

Or if these brackets can be used for other purposes, any advice is welcomed! Thanks!

like image 787
jake wong Avatar asked Jun 08 '15 02:06

jake wong


People also ask

Which are the 4 types of brackets?

They are parentheses, square brackets, curly brackets, and angle brackets.

What do parenthesis () and square bracket [] In differ?

The difference between a 'bracket' and a 'parentheses' can be a bit confusing. Generally, 'parentheses' refers to round brackets ( ) and 'brackets' to square brackets [ ]. However, we are more and more used to hearing these referred to simply as 'round brackets' or 'square brackets'.

What do round brackets mean in Python?

In general, I guess that square brackets are used mainly for lists and indexing things whereas rounded brackets are for calculations (as you would in maths) and functions etc.

What does two brackets mean in Python?

The single and double square brackets are used as indexing operators in R Programming Language. Both of these operators are used for referencing the components of R storage objects either as a subset belonging to the same data type or as an element.


2 Answers

[]: 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)
  • 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))

{}: Dictionaries and sets, as well as string formatting

  • Dicts: {}, {0: 10}, {i: i**2 for i in range(5)}
  • Sets: {0}, {i**2 for i in range(5)}
  • Inside f-strings and format strings, to indicate replacement fields: f'{foobar}' and '{}'.format(foobar)

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.

like image 196
Maltysen Avatar answered Sep 22 '22 12:09

Maltysen


() 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.

like image 39
Rampant Avatar answered Sep 22 '22 12:09

Rampant