improving a huge double-for cycle

giltay at giltay at
Thu Sep 18 19:26:49 CEST 2008

On Sep 18, 11:18 am, prueba... at wrote:
> dup=set()
> SN=[]
> for item in IN:
>    c=item.coordinates[0], item.coordinates[1]
>    if c in dup:
>       SN.append(item.label)
>    else:
>       dup.add(c)

+1 for O(N)

If item.coordinates is just an (x, y) pair, you can skip building c
and save a little memory:

seen_coords = set()

for node in IN:
    if node.coordinates in seen_coords:

seen_coords gets populated with references to the existing
node.coordinates objects, instead of new tuples.

Geoff G-T

More information about the Python-list mailing list