LN3
LN3

Reputation: 67

How to understand complex lists in python

Sorry this will be a very basic question, I am learning python.

I went through a coding exercise to calculate bmi and went for a straightforward way:

def bmi(weight, height):
    bmi = weight / height ** 2
    if bmi <= 18.5:
        return "Underweight"
    elif bmi <= 25:
        return "Normal"
    elif bmi <= 30:
        return "Overweight"
    else:
        return "Obese"

However, in the exercise solutions I also see this one:

def bmi(weight, height):
    b = weight / height ** 2
    return ['Underweight', 'Normal', 'Overweight', 'Obese'][(b > 30) + (b > 25) + (b > 18.5)]

I want to understand what this double/back-to-back list is where they've got [items][conditions] but I can't find the name of it to learn about it - what is the name for this? Is it a part of list comprehensions?

Upvotes: 1

Views: 91

Answers (1)

THUNDER 07
THUNDER 07

Reputation: 559

observe this line carefully

['Underweight', 'Normal', 'Overweight', 'Obese'][(b > 30) + (b > 25) + (b > 18.5)]

Above is line is actually list indexing [(b > 30) + (b > 25) + (b > 18.5)] this gives the index of the list ['Underweight', 'Normal', 'Overweight', 'Obese']. Let us say b > 30 then it satisfies all the three conditions (b > 30) + (b > 25) + (b > 18.5) the equivalent boolean value of each condition is 1 making the sum 3 and returns index 3 which is Obese. Similarly it works for other conditions.

Upvotes: 3

Related Questions