Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Possible to unpack tuple and append to multiple lists in one line?

Tags:

python

list

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)
like image 637
ZAR Avatar asked Feb 15 '18 00:02

ZAR


3 Answers

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))
like image 90
Sohaib Farooqi Avatar answered Oct 19 '22 02:10

Sohaib Farooqi


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)
like image 38
jpp Avatar answered Oct 19 '22 04:10

jpp


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)
like image 44
Olivier Melançon Avatar answered Oct 19 '22 03:10

Olivier Melançon