I have two sequence as below
t = [[1,2,3],[4,5,6],[7,8,9]]
alpha = ['a','b','c']
How to use list comprehension to modify t as below:-
t = [[1,2,3,'a'],[4,5,6,'b'],[7,8,9,'c']]
I have two sequence as below
t = [[1,2,3],[4,5,6],[7,8,9]]
alpha = ['a','b','c']
How to use list comprehension to modify t as below:-
t = [[1,2,3,'a'],[4,5,6,'b'],[7,8,9,'c']]
use zip:
t = [[1,2,3],[4,5,6],[7,8,9]]
alpha = ['a','b','c']
new_list = [a+[b] for a, b in zip(t, alpha)]
Output:
[[1, 2, 3, 'a'], [4, 5, 6, 'b'], [7, 8, 9, 'c']]
You could use zip to get corresponding pairs of elements, and from there it's just a matter of joining:
>>> t = [[1,2,3],[4,5,6],[7,8,9]]
>>> alpha = ['a','b','c']
>>> [x[0] + [x[1]] for x in zip(t,alpha)]
[[1, 2, 3, 'a'], [4, 5, 6, 'b'], [7, 8, 9, 'c']]
Iterate over the indices:
t = [[1,2,3],[4,5,6],[7,8,9]]
alpha = ['a','b','c']
print([t[i] + [alpha[i]] for i in range(len(alpha))])