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

Ben Finney ben+python at benfinney.id.au
Sat Sep 29 07:25:15 EDT 2018


Ben Finney <ben+python at benfinney.id.au> writes:

> 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 omits the important case you were concerned with: when `index <
len(words)` is false. In other words, that example fails to actually pad
the resulting list.

Try this instead::

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

-- 
 \       “When a well-packaged web of lies has been sold to the masses |
  `\    over generations, the truth will seem utterly preposterous and |
_o__)                    its speaker a raving lunatic.” —Dresden James |
Ben Finney




More information about the Python-list mailing list