Is there a way to not make my list disappear?

Question:

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]
Asked By: w kooij

||

Answers:

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)
Answered By: BokiX
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.