1

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 ]
asked Aug 28, 2020 at 18:59
1
  • look for zip(*polygon)? Commented Aug 28, 2020 at 19:01

2 Answers 2

3

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
2

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.