Search code examples
listcomparisonpython-3.9

Removing values from lists using comparisons (Python3)


I'm using Python3.

I have 2 lists for this example:

G1 = [0, 5, 10, 18, 24, 31, 40]

G2 = [0, 8, 15, 28, 37, 50, 61]

Is it possible to get Python to take the last element in a list (in G1 this is 40), and then remove every element from G2 whose value is < 40?

The end goal would be for G2 to read: [50, 61]


Solution

  • You can use list comprehension:

    G1 = [0, 5, 10, 18, 24, 31, 40]
    G2 = [0, 8, 15, 28, 37, 50, 61]
    
    G2 = [v for v in G2 if v >= G1[-1]]
    print(G2)
    

    Prints:

    [50, 61]