Q:

Curly bracket sets and sorting in python 3.2

Hi I have two questions:

I am trying to build sets of two using i.e. of the form example: new = [{24,33},{12,13},{17,19},....]. Basically I have data in the form of two lists say one is called N = [24,12,17,....] and the other is z = [33,13,19,....]. I have been trying to achieve this using:
new=[]
for i in range(len(z)):
    new.append({z[i]})
    new.extend({N[i]})
print(new)

and have tried many variations of append and extend with or without curly brackets.
Once 1) is achieved I would then like to rearrange new according to the size of the second item in each set, that is in ascending order of z, so I would like to get:
new=[{12,13},{17,19},{24,33}]

A:

Use zip() to pair two lists:
new = [{a, b} for a, b in zip(N, z)]

But sets are unordered so there is no 'second value'. You can sort on the minimum value perhaps:
new.sort(key=lambda s: min(s))

If you need to sort it on the values of z, do so before creating your sets:
from operator import itemgetter

new = [{a, b} for a, b in sorted(zip(N, z), key=itemgetter(1))]

But if these are really x, y coordinates, then just use zip() and sorted() to give you a sequence of tuples:
new = sorted(zip(N, z), key=itemgetter(1))

A set() contains only unique values:
>>> {1, 1}
set([1])

A tuple is an ordered (immutable) sequence instead:
>>> (1, 1)
(1, 1)

