What's an elegant way to test for list index existing?
Peter Otten
__peter__ at web.de
Sat Sep 29 08:10:42 EDT 2018
Ben Finney wrote:
> 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.
It would if it weren't a syntax error.
No harm done ;)
> 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)]
>
More information about the Python-list
mailing list