Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading