# sorting list of complex numbers

skip at pobox.com skip at pobox.com
Sun Nov 9 16:13:58 CET 2008

```    >> Is there a way to do this using just the key arg, no extra data
>> structures?

Duncan> Is a tuple an extra data structure?

>>>> lst.sort(key=lambda x: (x.real,x.imag))
>>>> pprint.pprint(lst)
Duncan> [2.6000000000000001j,
Duncan>  20j,
Duncan>  (1+2.73j),
Duncan>  (1+21j),
Duncan>  (2+2.8600000000000003j),
Duncan>  (2+22j),
Duncan>  (3+2.9900000000000002j),
Duncan>  (3+23j),
Duncan>  (4+3.1200000000000001j),
Duncan>  (4+24j),
Duncan>  (5+3.25j),
Duncan>  (5+25j),
Duncan>  (6+3.3799999999999999j),
Duncan>  (6+26j),
Duncan>  (7+3.5100000000000002j),
Duncan>  (7+27j),
Duncan>  (8+3.6400000000000001j),
Duncan>  (8+28j),
Duncan>  (9+3.77j),
Duncan>  (9+29j)]

Ah, thanks.  I'm still getting used to this key thing, always having relied
on the cmp arg.

Duncan> If you don't like the tuple then just do the two sorts separately:

>>>> lst.sort(key=lambda x: x.imag)
>>>> lst.sort(key=lambda x: x.real)
...

I tried that.  I could have sworn when I read through the output it hadn't
retained the order of the real parts.  Wait a minute...  I sorted by real
them by imag.  So the trick is to sort by primary sort key last.

Timeit suggests the single sort returning the real, imag tuples is faster
than two sorts each on one field, as you might expect since many fewer calls
to the key function are made.

Thanks,

Skip

```