guagay_wk
guagay_wk

Reputation: 28060

Add string to end of every tuple in a list of tuples

I have this list of tuples;

List = [('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]

I want to add a string to the end of every tuple inside this list. It will look like this;

OutputList = [('1', 'John', '129', '37', 'TestStr'), ('2', 'Tom', '231', '23', 'TestStr')]

I tried OutputList = [xs + tuple('TestStr',) for xs in List ] but it did not work out. What is the proper way to solve this?

I am using Python 2.7

Upvotes: 2

Views: 2246

Answers (2)

user2357112
user2357112

Reputation: 281538

If you want a 1-element tuple, that's ('TestStr',), not tuple('TestStr',):

OutputList = [xs + ('TestStr',) for xs in List]

tuple('TestStr',) is the same as tuple('TestStr'), since trailing commas are ignored in function calls. tuple('TestStr') treats 'TestStr' as an iterable and builds a tuple containing the characters of the string.

Upvotes: 6

Martijn Pieters
Martijn Pieters

Reputation: 1123520

Just remove the tuple part:

OutputList = [xs + ('TestStr',) for xs in List]

You don't need to the tuple() callable here, you are not converting one type to a tuple, all you need is a tuple literal here.

Demo:

>>> List = [('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]
>>> [xs + ('TestStr',) for xs in List]
[('1', 'John', '129', '37', 'TestStr'), ('2', 'Tom', '231', '23', 'TestStr')]

Upvotes: 3

Related Questions