Python: Append tuple to a set with tuples

Question:

Following is my code which is a set of tuples:

data = {('A',20160129,36.44),('A',20160201,37.37),('A',20160104,41.06)};
print(data);

Output: set([('A', 20160129, 36.44), ('A', 20160104, 41.06), ('A', 20160201, 37.37)])

How do I append another tuple ('A', 20160000, 22) to data?

Expected output: set([('A', 20160129, 36.44), ('A', 20160104, 41.06), ('A', 20160201, 37.37), ('A', 20160000, 22)])

Note: I found a lot of resources to append data to a set but unfortunately none of them have the input data in the above format. I tried append, | & set functions as well.

Asked By: DhiwaTdG

||

Answers:

the trick is to send it inside brackets so it doesn’t get exploded

data.update([('A', 20160000, 22)])
Answered By: Alexis Benichoux

just use data.add. Here’s an example:

x = {(1, '1a'), (2, '2a'), (3, '3a')}

x.add((4, '4a'))

print(x)

Output: {(3, '3a'), (1, '1a'), (2, '2a'), (4, '4a')}

Answered By: Peter Schorn
s = {('a',1)}
s.add(('b',2))

output: {(‘a’, 1),(‘b’, 2)}

s.update(('c',3))

output: {(‘a’, 1), 3, ‘c’, (‘b’, 2)}

There can be loss of generality by using update.

Better to use add.
It is a cleaner way of operating sets.

Answered By: Storm

This failure also matching the question title:

your_set = set
your_set.add(('A', 20160000, 22))

because it should be:

your_set = set()
Answered By: Paul Krush
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.