Home > Mobile >  Python list remove does opposite of condition specified
Python list remove does opposite of condition specified

Time:07-15

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)

CodePudding user response:

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]]

CodePudding user response:

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]]

  • Related