Base de compréhension de liste
list = [i for i in range(5)]
print(list) # [0,1,2,3,4]
list2 = [ i * i for i in range(10)]
print(list2) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
If dans compréhension de liste
list3 = [ n for n in range(10) if n % 2 == 0]
print(list3) # [0, 2, 4, 6, 8]
If imbriqués
list4 = [ n for n in range(10) if n % 2 == 0 if n >= 5]
print(list4) # [6, 8]
If…Else dans compréhension de liste
list5 = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(list5) #
list6 = [str(i) + ":Pair" if i%2==0 else str(i) + ":Impair" for i in range(10)]
print(list6)
# ['0:Pair', '1:Impair', '2:Pair', '3:Impair', '4:Pair', '5:Impair', '6:Pair', '7:Impair', '8:Pair', '9:Impair']