How can I extend a set using a tuple?

Unlike list.extend(L)in setthere is no function extend. How can I extend a tuple into a set using pythonic?

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)])

Expected Result:

set([1, 2, 3, 4, 5, 6, 7])

My solutions are something like:

for item in t1 :
    s.add(item)
+4
source share
3 answers

Try the method union-

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 pointed out in the comments, a cleaner method -

s = set().union(t1, t2, t3)
+12
source

Or:

>>> newSet = s.union(t1, t2, t3)
set([1, 2, 3, 4, 5, 6, 7])

Or the next one that actually updates without any redirects

>>> s.update( t1, t2, t3)
>>> s
set([1, 2, 3, 4, 5, 6, 7])
+8
source

You are using the wrong method. addadds one element, updatecombines a set with an argument.

t1 = (1, 2, 3)
t2 = (3, 4, 5)
t3 = (5, 6, 7)

s = set()
s.update(t1)
s.update(t2)
s.update(t3)

print s
+6
source

Source: https://habr.com/ru/post/1598919/


All Articles