How to call an element of a set?

Sorry for the very silly question. I’m trying to figure out how to call the elements of a set. For example in my below example, how do I get the first element, i.e., “Acg”?

A = Set([“Acg”, “Bdc”, “HH”]);

I tried, A[1], A(1), A{1}, but none of them worked.

The default Set in Base is not ordered - there is no “first” element. You may want to check out OrderedSet from DataStructures.jl instead, though usually depending on a specific ordering could also be served by using unique on a regular vector.

1 Like

I see.

Many thanks. In this case, it seems that Julia is trying to make something really simple really hard :slight_smile:

It’s a design choice like any other - the common case for a Set is to be unordered, it just happens that some languages like python leak some internal ordering or even guarantee an order, locking them into that decision for backwards compatibility reasons. If the default here is unordered, julia is free to optimize the internal datastructure as much as we want, changing the order to provide more efficient storage etc.

Sure it has its pros and cons, but to me that is a weird thing to be split on. It may also be worthwhile to think about why you need a specific ordering of a Set in the first place, and if a different datastructure may be better suited to the task at hand.


Python doesn’t guarantee a set order and Julia leaks the internal order just as much as Python does, e.g. with first(s).

Are you aware that you can use an array for this purpose? It is designed to retain the ordering of it’s elements:

A = ["Acg", "Bdc", "HH"]

Many thanks! That will do the trick.

This is probably the best solution. I wasn’t aware of it, because I’m a brand new Julia user. Many thanks!

A Set has a pretty mathematical meaning (i.e. unordered), it’s not just “a few items laid out in this way”.

Set also has no duplicates and different performance characteristics.