Reputation: 151
Experimentally, I was able to create one like this:
s = set(((1,2),))
>>> s
{(1, 2)}
>>> (1, 2) in s
True
but the syntax looks a bit overloaded. Can someone please explain why it has to be this way to work (three sets of parentheses and a comma)?
Upvotes: 2
Views: 1494
Reputation: 5965
The trailing ,
simply tells python that the value is a sequence, a tuple
in this case.
Parentheses are normally used in mathematical expressions. And they are also used to define tuples.
>>> (3 + 2)
5
>>> (10)
10
If there is only one element inside a pair of parentheses, it is considered as an expression and is evaluated, returning a single value.
In order to tell python explicitly that it's a tuple
, a ,
has to be added at the end.
>>> (10,)
(10,)
>>> t = 1,
>>> t
(1,)
>>> type(t)
<class 'tuple'>
Coming to your question,
s = set(((1,2),))
(1, 2)
is a tuple
.
((1, 2),)
is a tuple
of tuples (having only one tuple in this case).
Something similar to this,
>>> ((1, 2), (3, 4))
((1, 2), (3, 4))
with only the first element.
Converting ((1,2),)
to a set
will return a set
with (1, 2)
as the only element. The outermost pair of parentheses is simply the set
function call.
Upvotes: 0
Reputation: 41
To be clear, you want to validate that the tuple (1, 2)
is in s
? Taking advantage of python's flexibility for readability might help you understand why the number of parentheses is necessary.
set( # first paren is for calling the function set
( # second paren creates the object of items set should look at
(1,2), # is an item in the set
)
)
# output same as
set(((1,2), (1,2), (1,2)))
# output same as
t = ((1,2), (1,2), (1,2))
set(t)
# output same as
t = (1,2)
t = (t, t, t)
set(t)
# output same as
t = (1, 2)
set([t]*5)
set()
looks for all items in self
. If you are hoping for a more readable solution than set variables.
Upvotes: 0
Reputation: 24232
You could have used set([(1, 2)])
to achieve the same.
You have one set (no, no pun intended...) of parentheses for the function call. set()
takes an iterable as argument, the list that contains your only tuple.
If you want to use a tuple instead of a list, it gets a bit harder to read. The tuple equivalent of the list [item]
is the tuple (item,)
- the comma makes it a tuple, not the parentheses.
So, replacing my [ (1, 2) ]
with ( (1, 2), )
, you get your set(((1, 2),))
And, of course, as noted in the comments, {(1, 2)}
would be the easiest way to write it...
Upvotes: 3