spacing
spacing

Reputation: 780

How to add a string into a tuple to create a 2 member tuple?

Let's say I have a string

x = '32'

And I already have a 1 length tuple defined with something like

tuple_a = ('12',)

I want to transform the string into a 1 member tuple and add the 2 tuples together so the outcome is something like

tuple_a + x = ('12','32')

and not something like:

tuple_a + x = ('12','3','2')

Which is all I could managed to do by now.

Upvotes: 0

Views: 63

Answers (3)

Cory Kramer
Cory Kramer

Reputation: 117951

Tuples are immutable, so you cannot modify tuple_a to insert another element. You'd have to construct a new tuple, and assign that back to your tuple_a variable.

>>> x = '32'
>>> tuple_a = ('12',)
>>> tuple_a = (tuple_a[0], x)
>>> tuple_a
('12', '32')

As @iCodez mentioned, the + operator is defined for tuples, so you could take advantage of that too if you wish

>>> tuple_a = ('12',)
>>> tuple_a + (x,)
('12', '32')

Upvotes: 3

Ejaz
Ejaz

Reputation: 1632

You cannot modify a tuple. You will have to create a new one.

If you need to modify, better use a list.

x = '32'
list1 = ['12']
list1.append(x)
print list1  # ['12','32']

Upvotes: 0

Warren Weckesser
Warren Weckesser

Reputation: 114911

How about tuple_a + (x,)?

>>> tuple_a = ('12',)
>>> x = '32'
>>> tuple_a + (x,)
('12', '32')

Upvotes: 3

Related Questions