Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP list() equivalent in Python

Tags:

python

php

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

PHP:

list($first, $second, $third) = $myIndexArray;
echo "First: $first, Second: $second";
like image 396
Drew Avatar asked Mar 07 '12 08:03

Drew


1 Answers

>>> 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
like image 157
dhg Avatar answered Sep 28 '22 21:09

dhg