0

I face a strange problem where set comprehension won't work as intended.

b=[[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
print({(R, 0, 0) for _, R, _ in b})

We have output

{(12, 0, 0), (9, 0, 0), (7, 0, 0), (20, 0, 0), (24, 0, 0)}

Not the desired answer

{(9, 0, 0), (7, 0, 0), (12, 0, 0), (20, 0, 0), (24, 0, 0)}

What went wrong? For list comprehension, it works fine.

b=[[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
print([(R, 0, 0) for _, R, _ in b])

We have output

[(9, 0, 0), (7, 0, 0), (12, 0, 0), (20, 0, 0), (24, 0, 0)]

1 Answers1

0

It is natural to have sets comprehension looks like this. Based on Iain and juanpa's comment, sets are not ordered. The order is not preserved. So that's why we have "unintended" print value.
On the other hand, if you want to preserve the order, you should use lists.

  • `dict`s will preserve order as of 3.6 (as implementation detail)/3.7 (as language guarantee). It's often possible to construct a `dict` with keys you don't care about that mostly behaves like an insertion-ordered `set`. See the duplicates I linked. – ShadowRanger Nov 11 '22 at 03:10