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 -- http://mail.python.org/mailman/listinfo/python-list