0

Can anybody explain me why am I getting some errors with the following python code? The loop removes two tuple but one still in the list after the loop end. The print at the end is not the result i am expected.

>>> liste=[(1,2),(2,3),(3,1),(1,4),(3,4)]
>>> for couple in liste:
...    if int(1) in couple:
...        liste.remove(couple)
... 
>>> print(liste)
[(2, 3), (1, 4), (3, 4)]
  • What errors are you getting? – Danielle M. Sep 21 '16 at 21:04
  • You don't need to use `int(1)`; that's the same thing as `1`. The duplicate explains how to properly remove items from a list as you iterate. See [Loop "Forgets" to Remove Some Items](https://stackoverflow.com/q/17299581) or [Removing from a list while iterating over it](https://stackoverflow.com/q/6500888) for posts that explain why your attempt doesn't work. – Martijn Pieters Sep 21 '16 at 21:14
  • For future reference, you would need to include your *expected* output too, not just that the output you got was unexpected. – Martijn Pieters Sep 21 '16 at 21:15
  • I read the posts you suggested, i think i understand now why i didn't get the expected output. Sorry i didn't explain well my problem. Thanks @Martijn Pieters – sogloarcadius Sep 21 '16 at 21:23

1 Answers1

-3

After your for statement you should indent before starting the if statement.

liste=[(1,2),(2,3),(3,1),(1,4),(3,4)] for couple in liste:

        if int(1) in couple:

            liste.remove(couple)

print(liste) [(2, 3), (1, 4), (3, 4)]

Lampros Tzanetos
  • 323
  • 1
  • 2
  • 20