Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to not make my list disappear?

I’m trying to make some code, this part doesn’t work. Because it keeps saying my list index is out of range and it looks like items from my list are disappearing. If i take a look at the code I can’t find why it’s not working. Anyone any idea why this is not working?

ts = [[4, 5], [9, 6], [2, 10]]
repeats = 3
for i in range(repeats):
    cts = ts
    t = ts[i]
    cts.remove(t)
    print(ts, t)

###    [[6, 9], [2, 10]] [4, 5]
###    [[6, 9]] [2, 10]
###
###    Exception has occurred: IndexError
###    list index out of range
###
###      File "MyFile.py", line 12, in <module>
###        t = ts[i]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why this is happening is because you have cts = ts in every loop iteration. So you are modifying the original ts list.
This code should do what you need:

ts = [[4, 5], [9, 6], [2, 10]]
for i in range(len(ts)):
    cts = ts.copy()
    t = ts[i]
    cts.remove(t)
    print(ts, t)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading