In [53]: set2 = {1, 2, True, "hello"}
In [54]: len(set2) Out[54]: 3
In [55]: set2 Out[55]: {'hello', True, 2}
- 1
- 2
-
2You described an observation, but what is your question? – Klaus D. Apr 22 '21 at 07:46
-
1And since `1` and `True` are equal you get only one of those. – Matthias Apr 22 '21 at 07:50
-
Does this answer your question? [Sorting a set of values](https://stackoverflow.com/questions/17457793/sorting-a-set-of-values) – CoolCoder Apr 22 '21 at 07:52
-
@KlausD.my question is if its unordered then why am not getting True as output of set2 and why getting in set3. – Rambo Apr 22 '21 at 08:04
-
@Matthias yeah both the sets containing 1 , one getting only False and another False An True both...why the concept not applying on both sets same...am sorry if am sounding like fool. – Rambo Apr 22 '21 at 08:07
-
Try `print(set((True, 1)))` and compare it with `print(set((1, True)))`. – Matthias Apr 22 '21 at 08:35
-
i understand 1 and true are just same ..in both sets i put 1 and true .....and both ouput must have either 1 or true or both or both not ...what so ever but here my main concern is about only why getting different outputs// – Rambo Apr 22 '21 at 09:43
2 Answers
Use list instead :
set2 = [1, 4.3, 4, 5, "set", True, False]
print(set2)
# [1, 4.3, 4, 5, 'set', True, False]
set3 = [True, False, 1, 4.3, 5, 4, "set"]
print(set3)
# [True, False, 1, 4.3, 5, 4, 'set']
- 475
- 1
- 6
- 17
-
yeah we can use list in better way but just curious why this happening just because of different postions...because as it says sets are unoredered. – Rambo Apr 22 '21 at 08:10
In python (and also in most of the other computer programming languages and in mathematics too), sets are unordered.
So, the two sets {4.3,4,5,"set",True,False} {False, True, 4, 4.3, 5, 'set'} are just the same.
We cannot add 1 in a set which already contains True. Similarly, we cannot add 0 in a set which already contains False (and vice-versa). This is because 1 and True are essentially the same, and so are 0 and False.
So, if we add True in a set already containing 1, then True will not get added in the set (like set2),
and similarly
if we add 1 in a set already containing True, then 1 will not get added in the set (like set3) and so the outputs are different.
If order is important, lists can be used.
>>> list2=[1,4.3,4,5,"set",True,False]
>>> print(list2)
[1, 4.3, 4, 5, 'set', True, False]
>>> list3=[True,False,1,4.3,5,4,"set"]
>>> print(list3)
[True, False, 1, 4.3, 5, 4, 'set']
Side-note:
I used to use sets as they do not store duplicate values. So, if you do not want to add duplicate values again, and for that sake are using sets, then this is an alternative:
if x not in mylist:
list.append(x)
- 734
- 6
- 19
-
-
Because we cannot add `True` in a set. See [this](https://stackoverflow.com/questions/51505826/how-come-i-can-add-the-boolean-value-false-but-not-true-in-a-set-in-python/51505871) . – CoolCoder Apr 22 '21 at 08:15
-
-