Idiomatic way to unpack variable length list of maximum size n
First of all, think about why you want to do this.
However, given that you want to (1) pad with None
and (2) ignore extra variables, the code is easy:
a,b,c,d = (line.split() + [None]*4)[:4]
Obviously, the magic number has to be the same as the number of variables. This will extend what you have with the magic number, then trim back down to that length.
For an arbitrary iterable you can do:
import itertools
def padslice(seq,n):
return itertools.islice(itertools.chain(seq,itertools.repeat(None)), n)
This is the same pad-and-slice with itertools.
In python 3 you can use this
a, b, c, d, *_unused_ = line.split() + [None]*4
Edit
For large strings I suggest to use maxsplit
-argument for split (this argument also works in py2.7):
a, b, c, d, *_unused_ = line.split(None, 4) + [None]*4
Why 5? Otherwise the 4th element would consist the whole residual of the line.
Edit2 It is 4… It stops after 4 splits, not 4 elements
Fix the length of the list, padding with None
.
def fixLength(lst, length):
return (lst + [None] * length)[:length]