Is there a way to assign to multiple variables in a one-liner?
Let's say I have a list of 3D points and I want x, y and z lists.
polygon = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
# this works to get the expected result, but is not a single list comprehension
x = [x for x, y, z in polygon ]
y = [y for x, y, z in polygon ]
z = [z for x, y, z in polygon ]
I am thinking of something like:
x, y, z = [... for x, y, z in polygon ]
Joost Döbken
asked Aug 28, 2020 at 18:59
2 Answers 2
You can use zip()
function:
polygon = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
x, y, z = zip(*polygon)
print(x)
print(y)
print(z)
Prints:
(0, 1, 1, 0)
(0, 0, 1, 1)
(0, 0, 0, 0)
Or if you want lists instead of tuples:
x, y, z = map(list, zip(*polygon))
answered Aug 28, 2020 at 19:01
Unpack the list of tuples using zip()
:
polygon = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
x,y,z = zip(*polygon)
print(list(x))
print(list(y))
print(list(z))
OUTPUT:
[0, 1, 1, 0]
[0, 0, 1, 1]
[0, 0, 0, 0]
EDIT:
If you want the lists:
x,y,z = [list(a) for a in zip(*polygon)]
answered Aug 28, 2020 at 19:02
lang-py
zip(*polygon)
?