2

So I have an object:

class Particle(object):
    def __init__(self, x, y, vx, vy, ax, ay):
        self._x = int(x)
        self._y = int(y)
        self._vx = int(vx)
        self._vy = int(vy)
        self._ax = int(ax)
        self._ay = int(ay)
        # ...

I want to create an instance of that object from a list of numbers. How would I do that? Particle(list) doesn't work because it only inputs a list, not each value in the list. Thanks so much, I am sure there is a very obvious answer.

2 Answers 2

3

Precede your list name by a star:

def foo(a, b, c):
    print(a, b, c)

a = [1,2,3]
foo(*a)
# 1 2 3

The star unpacks the list, which gives 3 separate values.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! I knew there was a simple way to do what i wanted!
2

What you need is called "unpacking argument lists". Here's an example taken from the tutorial:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

Comments

Your Answer

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.