John Difool
John Difool

Reputation: 5702

Appending an element to a list of arrays (in the most concise idiomatic way)

I wrote this code:

alist = [[0], [1], [2]]
blist = [-1, 0, 1]

for a, b in zip(alist, blist):
    a.append(b)

output is [[0, -1], [1, 0], [2, 1]]

It works, but is there a way to remove the loop entirely?

Upvotes: 1

Views: 110

Answers (3)

Yannic Hamann
Yannic Hamann

Reputation: 5205

If you don't mind to have a list of tuples as a result, I find this solution very readable.

>>> alist = [[0], [1], [2]]
>>> blist = [-1, 0, 1] 
>>> import itertools as it
>>> list(zip(it.chain(*alist), blist))
[(0, -1), (1, 0), (2, 1)]

If you must have a list of lists:

list(list(el) for el in zip(it.chain(*alist), blist))

Basically, I am unpacking the variable alist into positional arguments, which I then pass to itertools.chain(). This results in a flat list [0, 1, 2]. After that, you can simple zip the two lists and get the desired result without using a for loop. It is not the fastest but a valid, possible solution.

Upvotes: 0

Eric Duminil
Eric Duminil

Reputation: 54223

Your code is fine IMHO. It's readable, concise and makes it clear that you want to modify alist in place.

If you want to avoid any explicit loop, you could work with numpy arrays and use np.stack:

import numpy as np
a = np.array([[0, 1], [1, 2], [2, 3]])
b = np.array([2, 3, 4])
np.column_stack([a, b])

It outputs:

array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

Upvotes: 1

Zenith
Zenith

Reputation: 245

>>> alist = [[0], [1], [2]]
>>> blist = [-1, 0, 1]
>>> [a + [b] for a, b in zip(alist, blist)]
[[0, -1], [1, 0], [2, 1]]

will do what you want (without modifying alist), though it's not pretty

Upvotes: 0

Related Questions