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

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Fri Sep 28 23:08:59 EDT 2018


On 9/28/18 2:00 PM, 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.

Do you care whether there are more than 5 entries in the list?  If not,
then just add two empty strings to the end of the list:

     fld.extend(["", ""])

If fld already contained 5 entries, then the extra two empty strings may
or may not affect the subsequent logic.  If possible extra entries
bother you, then truncate the list:

     fld = (fld + ["", ""])[:5]

Or add empty strings as long as the list contains 5 entries:

     while len(fld) < 5:
         fld.append("")

Which one is "better" or "best"?  Your call, depending on what your
criteria are.  I think the last one expresses the intent the most
clearly, but YMMV.



More information about the Python-list mailing list