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

Chris Green cl at isbd.net
Sun Sep 30 10:32:22 EDT 2018


Bart <bc at freeuk.com> 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.)

No, it doesn't matter, I just need at least 5.

-- 
Chris Green
·



More information about the Python-list mailing list