Search code examples
pythonfor-loopnested-loops

compare elements of a list one by one in python


so I want to write a simple code to compare elements of a list one by one.

I defined a simple list with dictionary elements and try following:

x = [{'price': 66, 'distance': 1}, {'price': 63, 'distance': 2} \
    , {'price': 64, 'distance': 3}, {'price': 75, 'distance': 5}, \
     {'price': 75, 'distance': 10}, {'price': 60, 'distance': 10}, \
     {'price': 50, 'distance': 10}, {'price': 55, 'distance': 13},\
     {'price': 63, 'distance': 2}]

def nested_skyline():
    y = x
    for i in x:
        for j in x:
            if i != j:
                if i == {'price': 55, 'distance': 10} and j == {'price': 55, 'distance': 13}:
                    print('this')
                if (i['price'] == j['price']) and (i['distance'] < j['distance']):
                    y.remove(j)
                elif (i['price'] < j['price']) and (i['distance'] <= j['distance']):
                    y.remove(j)

    return y

if __name__ == '__main__':
    print(nested_skyline())

but there is no stage with i = {'price': 55, 'distance': 10} and j = {'price': 55, 'distance': 13} and result of my code is:

[{'price': 66, 'distance': 1}, {'price': 63, 'distance': 2}, {'price': 60, 'distance': 10}, {'price': 50, 'distance': 10}, {'price': 55, 'distance': 13}, {'price': 63, 'distance': 2}]

I expected to see 'this' at the result and remove for example the dictionary {'price': 55, 'distance': 13}.

help me please. thanks.


Solution

  • Seems like you are aware that you shouldn't manipulate the list you're iterating through, but you missed one point:

    y = x
    

    This just makes y an alias of x, and any modification to y is also applied to x.

    Try y = x[:] or y = x.copy() or y = list(x) so y becomes a copy of x and can be safely modified in the loop.