On Thu, Mar 31, 2016 at 12:51 PM, Terry Reedy wrote:
> On 3/31/2016 11:24 AM, Peter Otten wrote:
>> try...except to the rescue:
>>
> def get(seq, index, default=None):
>>
>> ... try: return seq[index]
>> ... except IndexError: return default
>
>
> Replace IndexError with (IndexError, K
On 3/31/2016 11:24 AM, Peter Otten wrote:
Steven D'Aprano wrote:
Sometimes people look for a method which is equivalent to dict.get, where
they can set a default value for when the key isn't found:
py> d = {1: 'a', 2: 'b'}
py> d.get(999, '?')
'?'
The equivalent for sequences such as lists a
On 31.03.2016 17:07, Steven D'Aprano wrote:
Sometimes people look for a method which is equivalent to dict.get, where
they can set a default value for when the key isn't found:
py> d = {1: 'a', 2: 'b'}
py> d.get(999, '?')
'?'
The equivalent for sequences such as lists and tuples is a slice. I
On Thu, Mar 31, 2016 at 9:24 AM, Peter Otten <__pete...@web.de> wrote:
> But note:
>
def get(seq, index, default=None):
> ... return (seq[index:index+1] or [default])[0]
> ...
get("abc", -1, "default")
> 'default'
The discontinuity between -1 and 0 in indexing is a pain in the rear.
Steven D'Aprano wrote:
> Sometimes people look for a method which is equivalent to dict.get, where
> they can set a default value for when the key isn't found:
>
>
> py> d = {1: 'a', 2: 'b'}
> py> d.get(999, '?')
> '?'
>
>
> The equivalent for sequences such as lists and tuples is a slice. If
Sometimes people look for a method which is equivalent to dict.get, where
they can set a default value for when the key isn't found:
py> d = {1: 'a', 2: 'b'}
py> d.get(999, '?')
'?'
The equivalent for sequences such as lists and tuples is a slice. If the
slice is out of range, Python returns a