I want to make a set of tuples in which the order of tuples shouldn't matter. For eg.- If the tuples I want to add is :
[(1,2),(1,3),(2,1)]
It should output like this:
{(1,2),(1,3)}
Is there any efficient way of doing this in python?
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
A tuple is an ordered collection of items. An ordered collection keeps the items in the order you insert or initialize them. In other words, the order is preserved. This is in contrast to dictionaries or sets, where the order is not preserved (unordered collections).
Sorting a List by the Second Element of the Tuple. If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key. Unfortunately, Python does not allow you to specify the index of the sorting element directly.
For all intents and purposes, it does not matter, and the use of ordered tuples is just the convention.
You can apply sorted
and then tuple
, followed by conversion to set
:
res = set(map(tuple, map(sorted, L)))
print(res)
{(1, 2), (1, 3)}
Explanation
There are a couple of good reasons why you should not convert each tuple to set
as an initial step:
(1, 1, 2)
and (1, 2)
would become equal after conversion to set
.tuple({(1, 2)})
and tuple({(2, 1)})
are equal. While this may be true, it would be considered an implementation detail, since set
is considered to be unordered.Function composition
Function composition is not native to Python, but if you have access to the 3rd party toolz
library you can avoid nested map
:
from toolz import compose
tup_sort = compose(tuple, sorted)
res = set(map(tup_sort, L))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With