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

Alister alister.ware at ntlworld.com
Sun Sep 30 12:15:05 EDT 2018


On Sun, 30 Sep 2018 11:45:21 +0100, Bart wrote:

> On 30/09/2018 11:14, Chris Green wrote:
>> Chris Angelico <rosuav at gmail.com> wrote:
>>> On Sat, Sep 29, 2018 at 12:21 PM Chris Green <cl at isbd.net> 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.
>>>
>>> shlex.split(ln) + ["", ""]
>>>
>> Now that *is* neat, I will probably do this.
> 
> Won't it give you 7 entries, when shlex.split(ln) returns 5?
> 
> Or doesn't that matter? (In which case that's something not mentioned in
> the specification.)

if only 5 entries are required than simply prune off the extra using a 
slice as I suggested yesterday



-- 
<KnaraKat> DalNet is like the special olympics of IRC.  There's a lot of
           drooling goin' on and everyone is a 'winner'.



More information about the Python-list mailing list