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]
CodePudding user response:
For removing values from ts
, you can simple do this.
ts = [[4, 5], [9, 6], [2, 10]]
for _ in range(len(ts)):
del ts[-1] # You can use `0` as well
OR
ts = [[4, 5], [9, 6], [2, 10]]
del ts
CodePudding user response:
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)