jeudi 10 septembre 2020

Else statement gets ignored when using multiple if else statements in list comprehension

My problem statement is creating a list with numbers between 1 to 30 using list comprehension with conditions like: list should contain a if number is divisible by 15 and b if number is divisible by 5 and the number itself if it is divisible by 3.

I must implement it using List Comprehension only so don't suggest other methods.

This was my initial approach:

list=["a" if i%15 is 0
else "b" if i%5 is 0
else i if i%3 is 0
for i in range(1,31)
]

This gives syntax error at for .

So I tried this:

list=["a" if i%15 is 0
    else "b" if i%5 is 0
    else i 
    for i in range(1,31)
    if i%3 is 0
    ]

But this ends up ignoring the first else condition and gives me the following output.

[3,6,9,12,'a',18,21,24,27,"a"]

Now I don't understand why the else condition is being ignored here. I am relatively new to python so can someone explain where I am making a mistake here. Like what would be the equivalent if else block code for what I have written not the correct one for my problem statement (I know that).

Also I don't understand why this would work.

list=["a" if i%15 is 0
    else "b" if i%5 is 0
    else i
    for i in range(1,31)
    ]

The output this gives is obviously not the right one for my problem statement but I am curious how not having an if condition at the end makes it work properly.

Aucun commentaire:

Enregistrer un commentaire