How to access the low digits of a list

Ian Kelly ian.g.kelly at gmail.com
Wed Jun 3 18:36:21 EDT 2015


On Wed, Jun 3, 2015 at 3:08 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> On Tuesday, June 2, 2015 at 7:50:58 PM UTC+5:30, Ian wrote:
>> On Tue, Jun 2, 2015 at 6:35 AM, Rustom Mody  wrote:
>> > For that matter even this works
>> > But I am not sure whats happening or that I like it
>> >
>> >>>> [x[-2:]  for x in lines]
>> > ['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']
>>
>> x[-2:] selects all items in the sequence with index i such that len(x)
>> - 2 <= i < len(x). For a sequence of length 2 or less, that's the
>> entire sequence.
>
> Thanks -- learn something
> So it means that indices can give indexerror; slices cannot?
> Seems fair enough put that way, but is visually counterintuitive

Yes. The rule I paraphrased above is stated at
https://docs.python.org/3/library/stdtypes.html#common-sequence-operations
-- scroll down to note 4. I don't know if there's anything that
clearly states that sequence slicing can't raise IndexError, but it is
at least implied by the above, and it is certainly true of all builtin
sequence types.



More information about the Python-list mailing list