Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #106167

Re: Slice equivalent to dict.get

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: Slice equivalent to dict.get
Date 2016-03-31 17:24 +0200
Organization None
Message-ID <mailman.265.1459437901.28225.python-list@python.org> (permalink)
References <56fd3d17$0$1606$c3e8da3$5496439d@news.astraweb.com>

Show all headers | View raw


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 the
> slice is out of range, Python returns a empty sequence:
> 
> py> L = [2, 4, 8, 16]
> py> L[5]  # out of range, raises IndexError
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> IndexError: list index out of range
> py> L[5:6]  # out of range slice return empty list
> []
> 
> To get a default:
> 
> py> L[5:6] or -1
> -1
> 
> 
> This is short and simple enough to use in place, but we can also wrap this
> into a convenient helper function:
> 
> def get(seq, index, default=None):
>     return (seq[index:index+1] or [default])[0]
> 
> 
> 
> py> get(L, 2, -1)
> 8
> py> get(L, 200, -1)
> -1

But note:

>>> def get(seq, index, default=None):
...     return (seq[index:index+1] or [default])[0]
... 
>>> get("abc", -1, "default")
'default'

God old try...except to the rescue:

>>> def get(seq, index, default=None):
...     try: return seq[index]
...     except IndexError: return default
... 
>>> get("abc", -1, "default")
'c'

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Slice equivalent to dict.get Steven D'Aprano <steve@pearwood.info> - 2016-04-01 02:07 +1100
  Re: Slice equivalent to dict.get Peter Otten <__peter__@web.de> - 2016-03-31 17:24 +0200
  Re: Slice equivalent to dict.get Ian Kelly <ian.g.kelly@gmail.com> - 2016-03-31 09:43 -0600
  Re: Slice equivalent to dict.get "Sven R. Kunze" <srkunze@mail.de> - 2016-03-31 18:05 +0200
  Re: Slice equivalent to dict.get Terry Reedy <tjreedy@udel.edu> - 2016-03-31 13:51 -0400
  Re: Slice equivalent to dict.get Zachary Ware <zachary.ware+pylist@gmail.com> - 2016-03-31 14:28 -0500

csiph-web