jeudi 1 octobre 2015

A combination of for loop & if-statement is giving an unexpected result [duplicate]

This question already has an answer here:

I tried to run the below code:

lstt = [1, 8, 6, 5, 9, 7, 3, 2, 4]
for possb in lstt :
    if possb in [6, 7, 1] or possb in [6, 5, 2, 9] or possb in [6, 5, 7] : 
        lstt.remove(possb)
print lstt

I got the following output:

[8, 5, 7, 3, 4]

whereas the expected output was:

[8, 3, 4]

I tried a different code, intended to achieve the same purpose:

lstt = [1, 8, 6, 5, 9, 7, 3, 2, 4]
for possb in lstt:
    if possb in [6, 7, 1] : lstt.remove(possb)
    elif possb in [6, 5, 2, 9] : lstt.remove(possb)
    elif possb in [6, 5, 7] : lstt.remove(possb)
print lstt

but got the same unexpected result.

I tried the above code on Python 2.7.10 [64-bit] on windows 7 64-bit. I got the same results on Python 3.4.3 [64-bit] (change print syntax).

So, give a solution to make the above program yield correct result, or why is the above code not working?

Aucun commentaire:

Enregistrer un commentaire