0

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.

2
  • 1
    A tuple is immutable, so you have to create a new tuple. Commented Nov 16, 2022 at 14:20
  • 4
    Does this answer your question? Add Variables to Tuple Commented Nov 16, 2022 at 14:22

3 Answers 3

2

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')]
Sign up to request clarification or add additional context in comments.

5 Comments

What would be the correct syntax if color is a list with the same length as a?
@AndreyKazak I added an example for this use case.
Dear Matthias, kudos to you!
Can the example for color list be improved for handling the following case: a = [[('1', 'hello', 'en'), ('2', 'hi', 'en')], ('3', 'dd', 'fr'), ('4', 'hi', 'ger')], where the 1st element is not a tuple, but a list of two (or more) tuples? It it better to handle using for loop, but not list comprehension?
@AndreyKazak I added a code example for that.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.