-1

I'm trying to remove elements which have cost>gas but opposite getting printed [[2, 4], [4, 1], [5, 2]]

def canCompleteCircuit(gas,cost):

        pair=[[a,b] for a,b in zip(gas,cost)] #gas,cost

        for a in pair:

            if(a[1]>a[0]):
                pair.remove(a)

        print(pair)

gas=[1,2,3,4,5]
cost = [3,4,5,1,2]

canCompleteCircuit(gas,cost)
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • 4
    don't mutate the list you're iterating over – QwertYou Jul 15 '22 at 12:47
  • Add some simple debugging statements here. For example `print(a)` when you enter the `for` loop. Does it always print what you expected? No, it doesn't. It only prints 3 gas/cost pairs instead of 5. Why? Because you [mutated](https://stackoverflow.com/questions/1637807/modifying-list-while-iterating) the `pairs` list as you were iterating over it. – jarmod Jul 15 '22 at 12:56
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – sahasrara62 Jul 15 '22 at 13:00

2 Answers2

2

Instead of removing try to create a new list:

>>> [[g,c] for g, c  in zip(gas, cost) if g >= c]
[[4, 1], [5, 2]]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
1

Why don't you use a simple list comprehension?

out = [[g,c] for g,c in zip(gas,cost) if g>=c]

output: [[4, 1], [5, 2]]

mozway
  • 194,879
  • 13
  • 39
  • 75