Keaire
Keaire

Reputation: 899

Add elements of a list at the end of each tuple of a list of tuples

I have a list with some static elements:

['foo', 1, '', 0]

And I have a list of tuples:

[('val1', 9), ('val2', 'val3'), ('val4', '')]

How can I add the elements of a list at the end of each tuple of a list of tuples?

Output

[
('val1', 9, 'foo', 1, '', 0),
('val2', 'val3', 'foo', 1, '', 0),
('val4', '', 'foo', 1, '', 0)
]

Upvotes: 2

Views: 1525

Answers (3)

M. Perier--Dulhoste
M. Perier--Dulhoste

Reputation: 1039

You can use tuple unpacking for this:

elts = ['foo', 1, '', 0]
t = [('val1', 9), ('val2', 'val3'), ('val4', '')]

result = [(*t_item, *elts) for t_item in t]

And it gives:

[('val1', 9, 'foo', 1, '', 0),
 ('val2', 'val3', 'foo', 1, '', 0),
 ('val4', '', 'foo', 1, '', 0)]

It is a little bit faster than https://stackoverflow.com/a/54409510/8056572 with large list t:

elts = ['foo', 1, '', 0]
t = [('val1', 9), ('val2', 'val3'), ('val4', '')] * 1000

%timeit [(*t_item, *elts) for t_item in t]
307 µs ± 2.45 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit [e + tuple(elts) for e in t]
432 µs ± 10.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Upvotes: 0

Picachieu
Picachieu

Reputation: 3782

In python, tuples are immutable collections, meaning you cannot modify the elements within it. However, you can reassign the variable to a new tuple, which can be used much like lists.

list1 = ['foo', 1, '', 0]
list2 = [('val1', 9), ('val2', 'val3'), ('val4', '')]
endlist = []
for x in range(len(list2)):
    endlist += [tuple(list2[x]) + tuple(list1)]

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140266

just rebuild the tuple list using addition of tuples:

elts = ['foo', 1, '', 0]
t = [('val1', 9), ('val2', 'val3'), ('val4', '')]

result = [e+tuple(elts) for e in t]

result:

[('val1', 9, 'foo', 1, '', 0),
 ('val2', 'val3', 'foo', 1, '', 0),
 ('val4', '', 'foo', 1, '', 0)]

you may want to set elts as tuple to avoid the conversion in the loop:

elts = ['foo', 1, '', 0] # or elts = tuple(elts) if you have an existing list
result = [e+elts for e in t]

Upvotes: 3

Related Questions