0

here is my code:

lst=[[6,7],[8,9],[10,11], [12, 14], [13, 18]]
lst.sort()
lst1=[]
for i in range(len(lst)-1):
    if lst[i][-1]<lst[i+1][0]:
        lst1.append(lst[i])
print(f'lst1 = {lst1}')
for i in lst:
    if i in lst1:
        lst.remove(i)
print(lst,'and',lst1)

and here is the result:

lst1 = [[6, 7], [8, 9], [10, 11]]
[[8, 9], [12, 14], [13, 18]] and [[6, 7], [8, 9], [10, 11]]

I don't know why [6,7] and [10,11] were removed but [8,9] still there, how can I fix it?

Thien Anh
  • 15
  • 3

1 Answers1

0

Iterate over the copy of the list instead of the list:

for i in lst[:]:
    if i in lst1:
        lst.remove(i)

Let's see the problem:

[[6, 7], [8, 9], [10, 11], [12, 14], [13, 18]]

When you iterate over the list, you remove the first element. So the list is now:

[[8, 9], [10, 11], [12, 14], [13, 18]]

[8,9] has shifted to the first position, but iterations only go forward. So now [10,11] is removed.

So the left part:

[[8, 9], [12, 14], [13, 18]]