[Tutor] multiple assignment

John Fouhy john at fouhy.net
Tue Oct 18 07:28:43 CEST 2005


On 18/10/05, Vincent Gulinao <vincent.gulinao at gmail.com> wrote:
> I was fascinated when I learned that I can do this in Python:
>
>  (str1, str2, str3, rest) = str.split(" ", 3)
> [...]
>  In essence, I'd like to capture the first 3 words in a string. If str is
> less than 3 words then any or all of the containers could have a None value.

I'm not aware of any simple syntax... You could do something with
itertools.  eg:

>>> from itertools import islice, chain, repeat
>>> lst = [1, 2, 3]
>>> a, b, c, d, e, f, g = islice(chain(lst, repeat(None)), 7)
>>> print a, b, c, d, e, f, g
1 2 3 None None None None
>>> a, b, c, d = islice(chain(lst, repeat(None)), 4)
>>> print a, b, c, d
1 2 3 None
>>> a, b = islice(chain(lst, repeat(None)), 2)
>>> print a, b
1 2

Not quite as elegant as the simple case, but it's the best I can think
of right now...

--
John.


More information about the Tutor mailing list