MarcelKlockman
MarcelKlockman

Reputation: 117

Append list elements to a list of tuples

a = [(1, "X"), (2, 'Y')]
b = [(1, 'Z'), (2, 'K')]
c = [t[1] for t in b]

d = []
i=0
for element in a:
    d.append(element + (c[i],))
    i += 1

print d

Gives me my desired output [(1, 'X', 'Z'), (2, 'Y', 'K')]

However this seems an unnecessarily long winded way of getting there. Is there a more efficient way (in terms of code) to achieve the same outcome?

Upvotes: 0

Views: 795

Answers (2)

user2390182
user2390182

Reputation: 73498

Use zip:

d = [x + y[1:] for x, y in zip(a, b)]

Or map:

d = map(lambda x, y: x + y[1:], a, b)

zip creates a list of tuples of correspondent elements in parallel iterables:

a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [4, 5, 6]
# zip(a, b, c): [(1, 'a', 4), (2, 'b', 5), (3, 'c', 6)]

Upvotes: 3

user3850
user3850

Reputation:

The data structures seem a bit unusual, but here is one way to get to your result.

a = [(1, "X"), (2, 'Y')]
b = [(1, 'Z'), (2, 'K')]

a1, a2 = zip(*a)  # -> a1 = (1, 2); a2 = ('X', 'Y')
_, b2 = zip(*b)   # -> b2 = ('Z', 'K')

d = zip(a1, a2, b2)

a1, a2 and b2 are only necessary, because a and b themselves are rather cumbersome.

If the tuples in a and b are always numbered sequentially from 1, why have the index at all?

a = ('X', 'Y')
b = ('Z', 'K')

d = zip(a, b)  # -> [('X', 'Z'), ('Y', 'K')]

and if you need the index, you can always enumerate():

for i, e in enumerate(d, 1):
    print i, e

Upvotes: 0

Related Questions