Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extend a set with a tuple?

Tags:

python

set

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)
like image 642
SparkAndShine Avatar asked Jul 21 '15 15:07

SparkAndShine


2 Answers

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)
like image 145
Anand S Kumar Avatar answered Sep 25 '22 21:09

Anand S Kumar


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])
like image 32
vogomatix Avatar answered Sep 22 '22 21:09

vogomatix