In python, Is it possible to unpack a tuple and append to multiple lists?
Instead of
x, y, z = (1, 2, 3)
x_list.append(x)
y_list.append(y)
z_list.append(z)
Is it possible to do this in one line?
x_list, y_list, z_list ~ (1, 2, 3)
You can do it like this
>>> t = (1,2,3)
>>> x,y,z = [1,2,3],[4,5,6],[7,8,9]
>>> x[len(x):],y[len(y):],z[len(z):] = tuple(zip(t))
>>> x
>>> [1,2,3,1]
>>> y
>>> [4,5,6,2]
>>> z
>>> [7,8,9,3]
If you wish to insert at start you can do
>>> x[:0],y[:0],z[:0] = tuple(zip(t))
You can't do this easily, at least not without overhead.
But what you can do is use a loop to give your code some structure.
for lst, j in [(x_list, x), (y_list, y), (z_list, z)]:
lst.append(j)
Another way this can be processed:
lst = (x_list, y_list, z_list)
num = (1, 2, 3)
for i, j in zip(lst, num):
i.append(j)
I don't think there is a canonical way, but suppose you have lists l1
, l2
and l3
, you can do this.
l1[len(l1):], l2[len(l2):], l3[len(l3):] = [1], [2], [3]
This is closer to the behaviour of extend
than append
.
If that doesn't suit you, you can also one-line it with zip
and a for-loop.
for l, el in zip((l1, l2, l3), (x, y, z)): l.append(el)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With