default value in a list

Jeff Shannon jeff at ccvcorp.com
Sat Jan 22 02:04:11 CET 2005


TB wrote:

> Hi,
> 
> Is there an elegant way to assign to a list from a list of unknown
> size?  For example, how could you do something like:
> 
> 
>>>> a, b, c = (line.split(':'))
> 
> if line could have less than three fields?

(Note that you're actually assigning to a group of local variables, 
via tuple unpacking, not assigning to a list...)

One could also do something like this:

 >>> l = "a:b:c".split(':')
 >>> a, b, c, d, e = l + ([None] * (5 - len(l)))
 >>> print (a, b, c, d, e)
('a', 'b', 'c', None, None)
 >>>

Personally, though, I can't help but think that, if you're not certain 
how many fields are in a string, then splitting it into independent 
variables (rather than, say, a list or dict) *cannot* be an elegant 
solution.  If the fields deserve independent names, then they must 
have a definite (and distinct) meaning; if they have a distinct 
meaning (as opposed to being a series of similar items, in which case 
you should keep them in a list), then which field is it that's 
missing?  Are you sure it's *always* the last fields?  This feels to 
me like the wrong solution to any problem.

Hm, speaking of fields makes me think of classes.

 >>> class LineObj:
...     def __init__(self, a=None, b=None, c=None, d=None, e=None):
...         self.a = a
...         self.b = b
...         self.c = c
...         self.d = d
...         self.e = e
...
 >>> l = "a:b:c".split(':')
 >>> o = LineObj(*l)
 >>> o.__dict__
{'a': 'a', 'c': 'c', 'b': 'b', 'e': None, 'd': None}
 >>>

This is a bit more likely to be meaningful, in that there's almost 
certainly some logical connection between the fields of the line 
you're splitting and keeping them as a class demonstrates that 
connection, but it still seems a bit smelly to me.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list