0

Brackets or parentheses

I find it difficult to know when to use brackets or parentheses. E.g. numbers = list(range(3, 8)) Here I expect brackets, but it's not.

26th Mar 2017, 12:13 AM
Wenwin
3 Answers
0
Brackets -- "[]" -- are used to get an item out of a list or dictionary. Here are some examples: >>> a = [1,2,3,4] >>> a[2] 3 >>> b = { 'age': 32, 'iq': 140, 'weight': 125 } >>> b['iq'] 140 Brackets may also be used to create a list comprehension. For example, here's one way to create a list of numeric strings containing the numbers from 1 to 10. >>> [str(_) for _ in range(1, 11)] ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] Parentheses are used when we're calling a function. In the example in your question -- list(range(3,8)) -- list and range are functions. Parentheses are also used to group parts of an expression. For example, >>> q = 3 * (2 + 5) >>> q 21 >>> p = 3 * 2 + 5 >>> p 11
26th Mar 2017, 11:07 AM
tom barron
0
Thank you very much for your very clear explanation. It makes sense now. I don't have to doubt anymore.
26th Mar 2017, 7:57 PM
Wenwin
0
() - tuples, functions, math [] - lists, splicing i.e (1,2)[0] == 1, [1,2,3,4][1] == 1, {1: 1,2:2,3:3}[2] == 2 {} - maps/dictionaries depending on what you call them
26th Mar 2017, 9:03 PM
Logan New
Logan New - avatar