Re: Slice equivalent to dict.get

2016-03-31 Thread Zachary Ware
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

Re: Slice equivalent to dict.get

2016-03-31 Thread Terry Reedy
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

Re: Slice equivalent to dict.get

2016-03-31 Thread Sven R. Kunze
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

Re: Slice equivalent to dict.get

2016-03-31 Thread Ian Kelly
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.

Re: Slice equivalent to dict.get

2016-03-31 Thread Peter Otten
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

Slice equivalent to dict.get

2016-03-31 Thread Steven D'Aprano
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