Is there any equivalent to the PHP list() function in python? For example:
PHP:
list($first, $second, $third) = $myIndexArray;
echo "First: $first, Second: $second";
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With