Home > Back-end >  Python list of tuples: increase number of tuple members
Python list of tuples: increase number of tuple members

Time:11-17

I have a list of tuples with the pattern "id", "text", "language" like this:

a = [('1', 'hello', 'en'), ...]

I would like to increase number of tuple members to "id", "text", "language", "color":

b = [('1', 'hello', 'en', 'red'), ...]

What is the correct way of doing this?

Thank you.

CodePudding user response:

Since a tuple is immutable you have to create new tuples. I assume you want to add this additional value to every tuple in the list.

a = [('1', 'hello', 'en'), ('2', 'hi', 'en')]
color = 'red'

a = [(x   (color,)) for x in a]
print(a)

The result is [('1', 'hello', 'en', 'red'), ('2', 'hi', 'en', 'red')].


If you have multiple colors in a list with as many entries as you have in your list with the tuples you can zip both sets of data.

a = [('1', 'hello', 'en'), ('2', 'hi', 'en'), ('3', 'oy', 'en')]
colors = ['red', 'green', 'blue']

a = [(x   (color,)) for x, color in zip(a, colors)]
print(a)

Now the result is

[('1', 'hello', 'en', 'red'), ('2', 'hi', 'en', 'green'), ('3', 'oy', 'en', 'blue')]

CodePudding user response:

tuples are immutable so you cannot append(). If you want to add stuffs you should use python lists. Hope, that might help you!

CodePudding user response:

You can convert the tuple to a list, change it, and then converting back to a tuple

a[0] = list(a[0])
a[0].append("red")
a[0] = tuple(a[0])

Just loop this for the entire list and it should work

  • Related