how to add value to a tuple?

PythonTuples

Python Problem Overview


I'm working on a script where I have a list of tuples like ('1','2','3','4'). e.g.:

list = [('1','2','3','4'),
        ('2','3','4','5'),
        ('3','4','5','6'),
        ('4','5','6','7')]

Now I need to add '1234', '2345','3456' and '4567' respectively at the end of each tuple. e.g:

list = [('1','2','3','4','1234'),
        ('2','3','4','5','2345'),
        ('3','4','5','6','3456'),
        ('4','5','6','7','4567')]

Is it possible in any way?

Python Solutions


Solution 1 - Python

Tuples are immutable and not supposed to be changed - that is what the list type is for.

However, you can replace each tuple using originalTuple + (newElement,), thus creating a new tuple. For example:

t = (1,2,3)
t = t + (1,)
print(t)
(1,2,3,1)

But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.

And another hint: Do not overwrite the built-in name list in your program, rather call the variable l or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.

Solution 2 - Python

Based on the syntax, I'm guessing this is Python. The point of a tuple is that it is immutable, so you need to replace each element with a new tuple:

list = [l + (''.join(l),) for l in list]
# output:
[('1', '2', '3', '4', '1234'), 
 ('2', '3', '4', '5', '2345'), 
 ('3', '4', '5', '6', '3456'), 
 ('4', '5', '6', '7', '4567')]

Solution 3 - Python

As mentioned in other answers, tuples are immutable once created, and a list might serve your purposes better.

That said, another option for creating a new tuple with extra items is to use the splat operator:

new_tuple = (*old_tuple, 'new', 'items')

I like this syntax because it looks like a new tuple, so it clearly communicates what you're trying to do.

Using splat, a potential solution is:

list = [(*i, ''.join(i)) for i in list]

Solution 4 - Python

In Python, you can't. Tuples are immutable.

On the containing list, you could replace tuple ('1', '2', '3', '4') with a different ('1', '2', '3', '4', '1234') tuple though.

Solution 5 - Python

As other people have answered, tuples in python are immutable and the only way to 'modify' one is to create a new one with the appended elements included.

But the best solution is a list. When whatever function or method that requires a tuple needs to be called, create a tuple by using tuple(list).

Solution 6 - Python

I was going through some details related to tuple and list, and what I understood is:

  • Tuples are Heterogeneous collection data type
  • Tuple has Fixed length (per tuple type)
  • Tuple are Always finite

So for appending new item to a tuple, need to cast it to list, and do append() operation on it, then again cast it back to tuple.

>But personally what I felt about the Question is, if Tuples are supposed to be finite, fixed length items and if we are using those data types in our application logics then there should not be a scenario to appending new items OR updating an item value in it. So instead of list of tuples it should be list of list itself, Am I right on this?

Solution 7 - Python

    list_of_tuples = [('1', '2', '3', '4'),
                      ('2', '3', '4', '5'),
                      ('3', '4', '5', '6'),
                      ('4', '5', '6', '7')]
    
    
    def mod_tuples(list_of_tuples):
        for i in range(0, len(list_of_tuples)):
            addition = ''
            for x in list_of_tuples[i]:
                addition = addition + x
            list_of_tuples[i] = list_of_tuples[i] + (addition,)
        return list_of_tuples
    
    # check: 
    print mod_tuples(list_of_tuples)

Solution 8 - Python

A lot of people is writing tuples are immutables... and that's right! But there is this code:

tuple = ()
for i in range(10):
    tuple += (i,)
print(tuple)

And It works! Why? Well.. that's because in the code there is a "=". Every time you use the operator "=" in Python you assign a new value to an object: you create a new variable!

So you are not modifying the old tuple: you are creating a new one, with the same name (tuple), with value the old one plus something more.

Solution 9 - Python

OUTPUTS = []
for number in range(len(list_of_tuples))):
    tup_ = list_of_tuples[number]
    list_ = list(tup_)  
    item_ = list_[0] + list_[1] + list_[2] + list_[3]
    list_.append(item_)
    OUTPUTS.append(tuple(list_))

OUTPUTS is what you desire

Solution 10 - Python

In case of tuple and list, a very simple way can be (suppose) :
tpl = ( 3, 6, 9)
lst = [ 12, 15, 18]
my_tuple = tpl + tuple(lst)
print(my_tuple)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShahzadView Question on Stackoverflow
Solution 1 - PythonAndiDogView Answer on Stackoverflow
Solution 2 - PythonatpView Answer on Stackoverflow
Solution 3 - PythonTerrabitsView Answer on Stackoverflow
Solution 4 - PythonPablo Santa CruzView Answer on Stackoverflow
Solution 5 - PythonRyanView Answer on Stackoverflow
Solution 6 - PythonDipakView Answer on Stackoverflow
Solution 7 - PythonViktorView Answer on Stackoverflow
Solution 8 - PythonAndrea DiamantiniView Answer on Stackoverflow
Solution 9 - PythonQuestwalkerView Answer on Stackoverflow
Solution 10 - PythonAryan DhawanView Answer on Stackoverflow