Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Append tuple to a set with tuples

Tags:

python

set

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.

like image 817
DhiwaTdG Avatar asked Sep 02 '16 15:09

DhiwaTdG


People also ask

How do you add a tuple to a tuple of tuples?

Append an item to tuple tuple is immutable, but you can concatenate multiple tuples with the + operator. At this time, the original object remains unchanged, and a new object is generated. Only tuples can be concatenated. It cannot be concatenated with other types such as list .

Can I add a tuple to a set in Python?

You can also add tuples to a set. And like normal elements, you can add the same tuple only once.

Can you add 2 tuples together?

You can combine tuples to form a new tuple. The addition operation simply performs a concatenation with tuples. You can only add or combine same data types.

Can 2 tuples be added in Python?

The primary way in which tuples are different from lists is that they cannot be modified. This means that items cannot be added to or removed from tuples, and items cannot be replaced within tuples. You can, however, concatenate 2 or more tuples to form a new tuple. This is because tuples cannot be modified.


2 Answers

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

data.update([('A', 20160000, 22)])
like image 99
Alexis Benichoux Avatar answered Sep 20 '22 02:09

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')}

like image 21
Peter Schorn Avatar answered Sep 17 '22 02:09

Peter Schorn