Filling in a tuple from unknown size list
Dave Angel
davea at ieee.org
Fri Nov 27 16:45:30 CET 2009
Peter Otten wrote:
> boblatest wrote:
>
>
>> Hello all,
>>
>> (sorry for posting from Google. I currently don't have access to my
>> normal nntp account.)
>>
>> Here's my question: Given a list of onknown length, I'd like to be
>> able to do the following:
>>
>> (a, b, c, d, e, f) = list
>>
>> If the list has fewer items than the tuple, I'd like the remaining
>> tuple elements to be set to "None". If the list is longer, I'd like
>> the excess elements to be ignored.
>>
>> The code snippet below does what I want, I was just wondering if there
>> was an interesting "Pythonic" way of expressing the same thing.
>>
>> Thanks,
>> robert
>>
>> def iter_inf(li, n):
>> for i in range(n):
>> if i < len(li):
>> r = li[i]
>> else:
>> r = None
>> i += 1
>> yield r
>>
>>
>> li = ['a', 'b', 'c']
>> (a, b, c, d, e) = iter_inf(li, 5)
>> print a, b, c, d, e
>>
>
> Here's an alternative implementation that works with arbitrary iterables:
>
>
>>>> from itertools import chain, repeat, islice
>>>> a, b, c = islice(chain("a", repeat(None)), 3)
>>>> a, b, c
>>>>
> ('a', None, None)
>
>>>> a, b, c = islice(chain("abcde", repeat(None)), 3)
>>>> a, b, c
>>>>
> ('a', 'b', 'c')
>
> Peter
>
>
>
Python 3.x has some extension to the way tuple unpacking works, and may
solve this problem (or half of it). I'm too lazy this morning to look
it up.
In Python 2.x I can't see any better way than Peter's elegant solution.
I would originally have done the chain and repeat, but followed it by
[:3] slice notation. I suspect that building an actual list would be
cheap enough, but I like the islice better.
DaveA
More information about the Python-list
mailing list