Unlike list.extend(L)
, there is no extend
function in set
. How can I extend a tuple to a set in pythonic way?
t1 = (1, 2, 3)
t2 = (3, 4, 5)
t3 = (5, 6, 7)
s = set()
s.add(t1)
s.add(t2)
s.add(t3)
print s
set([(3, 4, 5), (5, 6, 7), (1, 2, 3)])
My expected result is:
set([1, 2, 3, 4, 5, 6, 7])
My solutions is something like:
for item in t1 :
s.add(item)
Try the union
method -
t1 = (1, 2, 3)
t2 = (3, 4, 5)
t3 = (5, 6, 7)
s= set()
s = s.union(t1)
s = s.union(t2)
s = s.union(t3)
s
>>> set([1, 2, 3, 4, 5, 6, 7])
Or as indicated in the comments , cleaner method -
s = set().union(t1, t2, t3)
Either:
>>> newSet = s.union(t1, t2, t3)
set([1, 2, 3, 4, 5, 6, 7])
Or the following, which actually updates without any assignation needed
>>> s.update( t1, t2, t3)
>>> s
set([1, 2, 3, 4, 5, 6, 7])
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