Drew
Drew

Reputation: 1777

PHP list() equivalent in Python

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

PHP:

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

Upvotes: 16

Views: 6664

Answers (1)

dhg
dhg

Reputation: 52681

>>> 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

Upvotes: 32

Related Questions