With or without the parentheses in the assignments does the same thing

Viewed 118

Why do the two code samples return the same result?

code sample A)

employees = ['Michael', 'Dwight', 'Jim', 'Pam', 'Ryan', 'Andy', 'Robert']
index4 = (employees[4]) # with brackets
print(index4)

code sample B)

employees = ['Michael', 'Dwight', 'Jim', 'Pam', 'Ryan', 'Andy', 'Robert']
index4 = employees[4] #without brackets 
print(index4)

Both result in 'Ryan'.

4 Answers

Why does the two code samples return the same result?

Because you are using parentheses as a grouping operator. This has nothing to do with lists:

a = (4)
print(a)
b = 4
print(b)

Let's look at some other examples:

c = (4 + 3) * 5
print(d)
d = 4 + 3 * 5
print(d)

Here you get two different results because the parentheses force the addition first, just as in arithmetic. Without the parentheses, the multiplication is first.

Similarly to your example, you could do this:

e = (4 + 3)

but again, these parentheses are not needed because the addition is the only operator.

Is it just good practice?

Use parentheses in mathematical expressions when they give the result you want or when they make the calculation more clear. Otherwise, leave them out.

In python, parenthesis are used for grouping and also for function calls. Python knows the difference because of context. foo(x +y) calls the function foo while foo * (x + y) does multiplication of the object in foo.

You should only use grouping when needed. Since

index4 = (employees[4])

is only grouping 1 thing, you shouldn't do it. In fact, if its obvious what the precedence is, don't use it. This is correct:

index4 = employees[4] + employees[2] + employees[3]

But you can use it when you want to keep your python statements from exceeding 80 characters per line

index4 = (employees[4] + employees[2] + employees[3]
    + employees[26])

Brackets are used in python in three main ways

  • to define tuples
  • to group code
  • to pass arguments into a method

In this specific case - there won't be any difference, as this is the second case. (a) is same as a. But, if there was a comma after a - then a tuple would've been created - (a,). One benefit of using ( for grouping code is that you can spread it into several lines for better formatting.

index4 = (
    employees[4]
)

This depends entirely on what you're trying to accomplish. If you're just assigning one particular value to index4, then without the parenthesis would be a better choice. Sure, both work well; but with the parenthesis, there is a doubt as to whether you want to create a tuple (especially it is easy to create a tuple but forgetting the extra comma).

index4 = employee[4] is concise. There is no ambiguity.

index4 = (employee[4]) isn't. Did you want to create a tuple but just forgot to add the comma? Sure, the variable itself does give evidence that you wish to set the 4th item in the list; but, after a few days, when you look back, are you sure?

Related