osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

What's an elegant way to test for list index existing?


jladasky at itu.edu wrote:

> On Friday, September 28, 2018 at 11:03:17 AM UTC-7, Chris Green wrote:
>> I have a list created by:-
>> 
>>     fld = shlex.split(ln)
>> 
>> It may contain 3, 4 or 5 entries according to data read into ln.
>> What's the neatest way of setting the fourth and fifth entries to an
>> empty string if they don't (yet) exist? Using 'if len(fld) < 4:' feels
>> clumsy somehow.
> 
> How about this?
> 
> from itertools import chain, repeat
> temp = shlex.split(ln)
> fld = list(chain(temp, repeat("", 5-len(temp))))

If you are OK with silently dropping extra entries

fld = list(islice(chain(shlex.split(ln), repeat("")), 5))

or its non-itertools equivalent

fld = (shlex.split(ln) + [""] * 5)[:5]

are also possible. Personally I consider none of these to be elegant.
If you are going to unpack the fld entries I'd do it in a function with 
default values:

>>> def use_args(foo, bar, baz, ham="", spam=""):
...     print("\n".join("{} = {!r}".format(*p) for p in locals().items()))
... 
>>> use_args(*shlex.split("a b c"))
spam = ''
ham = ''
baz = 'c'
foo = 'a'
bar = 'b'
>>> use_args(*shlex.split("a b c d"))
spam = ''
ham = 'd'
baz = 'c'
foo = 'a'
bar = 'b'

This has the advantage that it fails for the unforeseen cases:

>>> use_args(*shlex.split("a b c d e f"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: use_args() takes from 3 to 5 positional arguments but 6 were 
given
>>> use_args(*shlex.split("a b"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: use_args() missing 1 required positional argument: 'baz'