Python: can I unzip a tuple and add to multiple lists on the same line?

In python, is it possible to unzip a tuple and add to multiple lists?

Instead

x, y, z = (1, 2, 3)
x_list.append(x)
y_list.append(y)
z_list.append(z)

Is it possible to do this on one line?

x_list, y_list, z_list ~ (1, 2, 3)
+4
source share
4 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 want to insert at the beginning, you can do

>>> x[:0],y[:0],z[:0] = tuple(zip(t))
+3
source

You cannot 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)

In another way, this can be handled:

lst = (x_list, y_list, z_list)
num = (1, 2, 3)

for i, j in zip(lst, num):
    i.append(j)
+4
source

, , , l1, l2 l3, .

l1[len(l1):], l2[len(l2):], l3[len(l3):] = [1], [2], [3]

extend, append.

, zip for.

for l, el in zip((l1, l2, l3), (x, y, z)): l.append(el)
+3

Given the original input, you can map the function above the list to display each item as a list, and then unpack:

x, y, z = map(lambda x:[x], (1, 2, 3))
+1
source

Source: https://habr.com/ru/post/1693663/


All Articles