][Thread Next][Date Index
What's an elegant way to test for list index existing?
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
>> 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)]