samedi 9 janvier 2021

List Comprehension : Python, for and if statement?

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

1] correct output

for is before if

newlist1 = [x for x in fruits if "a" in x]

2] Error even though for is before if as in the above statement

newlist2 = [x for x in range(10) if x != 5 else 6]

3.] correct output

but here if and else is before for

newlist3 = [x if x != 5 else 6 for x in range(10)]

May I know why the statement 3 is rendering the output while statement 2 is throwing the error?

Aucun commentaire:

Enregistrer un commentaire