16

Is there any equivalent to the PHP list() function in python? For example:

PHP:

list($first, $second, $third) = $myIndexArray;
echo "First: $first, Second: $second";

1 Answer 1

32
>>> a, b, c = [1, 2, 3]
>>> print a, b, c
1 2 3

Or a direct translation of your case:

>>> myIndexArray = [1, 2, 3]
>>> first, second, third = myIndexArray
>>> print "First: %d, Second: %d" % (first, second)
First: 1, Second: 2

Python implements this functionality by calling the __iter__ method on the right-side expression and assigning each item to the variables on the left-side. This lets you define how a custom object should be unpacked into a multi-variable assignment:

>>> class MyClass(object):
...   def __iter__(self):
...     return iter([1, 2, 3])
... 
>>> a, b, c = MyClass()
>>> print a, b, c
1 2 3
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet. That's a whole lot more info than I needed, and that's awesome!

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.