Which brackets to use? [ ] vs ( )?

Used [ ] in retrieving element from lists. Unfortunately that gave an error on mission 3 (Lists and Loops) in introduction to python course. However when I had changed [ ] to ( ), I got the correct answer.

Link to mission page; https://app.dataquest.io/m/312/lists-and-for-loops/4/retrieving-multiple-list-elements

Here is the example;
avg_rating =(fb_rating_data[2] + insta_rating_data[2] + pandora_rating_data[2]) / 3

avg_rating =[fb_rating_data[2] + insta_rating_data[2] + pandora_rating_data[2]] / 3

Hi @saidulislam1356,

Square brackets ([]) are in fact meant to be used to index lists.

Round brackets produce the right answer in the example you listed because they merely indicate that the elements within them should be evaluated together before the division by 3 happens.

For example, if there were no round brackets:

fb_rating_data[2] + insta_rating_data[2] + pandora_rating_data[2] / 3

What would happen is only pandora_rating_data[2] would be divided by 3.

Adding the round brackets make it so the 3 values are added up together first before being divided by 3, to give you the right average:

(fb_rating_data[2] + insta_rating_data[2] + pandora_rating_data[2]) / 3

Hello @blueberrypudding85,

So if I understand correctly, I could use square brackets (without any hassle) to add all the lists if I would not have to divide the total by 3?

In case of adding and then dividing I am supposed to use round brackets ( ) to comply to BODMAS rule. The square brackets simply fails to do so.

Using square brackets there would not have had the outcome you wanted, because then you’d be making them into another list.

You can’t use square brackets and round brackets interchangeably! They have different syntactic meanings. The round brackets here served the purpose of forcing compliance to our intended BODMAS rule, as you correctly observed.

To expand on this slightly with an example:

total_rating =(fb_rating_data[2] + insta_rating_data[2] + pandora_rating_data[2]) 

The above code assigns a numerical value to the variable total_rating. In this case, inclusion of the round brackets doesn’t change anything, but I’m using them to illustrate the distinction between round brackets and square brackets anyway.

Below, if I use square brackets, I’m actually assigning a list of 1 element (this element being the sum of the 3 ratings) to the total_rating variable.

total_rating =[fb_rating_data[2] + insta_rating_data[2] + pandora_rating_data[2]]

Use print(type(total_rating)) to see the differences produced.

hey @blueberrypudding85

Why did you have [2] with all the apps in calculating the avg_rating.


1 Like

Because we’re trying to fetch the average rating from each original list. This rating was the value at index 2. So the fb_rating_data[2] was used to refer to that rating value.

1 Like