Filling in a tuple from unknown size list

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Nov 27 18:30:26 CET 2009


On Fri, 27 Nov 2009 04:18:08 -0800, boblatest wrote:

> 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.

I'd call that a code-smell. If I saw that in code, I'd think long and 
hard about why it was there and if I could eliminate the names a...f and 
just work directly with the list.

But if you really do need it, I think the simplest and best way is to use 
the technique Stefan suggested:

a, b, c, d, e, f = (list + [None]*6)[:6]

provided list is short. If you fear that list might be huge and copying 
it will be prohibitively expensive:

a, b, c, d, e, f = (list[:6] + [None]*6)[:6]



-- 
Steven



More information about the Python-list mailing list