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?


Chris Green <cl at isbd.net> writes:

> I have a list created by:-
>
>     fld = shlex.split(ln)
>
> It may contain 3, 4 or 5 entries according to data read into ln.

Because of what an index means for the 'list' type, that's equivalent to
saying "the result of `len(fld)` may be 3, 4, or 5".

> What's the neatest way of setting the fourth and fifth entries to an
> empty string if they don't (yet) exist?

You have the right idea: testing the length of the object is a correct
and expressive way to ask "is there an item at this index in the list".

> Using 'if len(fld) < 4:' feels clumsy somehow.

One reason I finx that clumsy is that you're testing against a
hard-coded value; and you'd have to write a loop to get the value each
time.

You can use a comprehension, iterating over the full range of index you
want::

    words = shlex.split(line)
    padding_length = 5
    words_padded = [
        (words[index] if index < len(words))
        for index in range(padding_length)]

That accomplishes the construction of the padded list in a single
expression, hopefully expressive, and definitely making use of whatever
optimisations the in-built comprehension mechanics provide.

-- 
 \       ?Pray, v. To ask that the laws of the universe be annulled in |
  `\     behalf of a single petitioner confessedly unworthy.? ?Ambrose |
_o__)                           Bierce, _The Devil's Dictionary_, 1906 |
Ben Finney