3

I like function get, where a default value can be supplied, but this work only on dictionary.

s=dict{}
s.get("Ann", 0)

I wrote somethin similar for list. Does this function already exist in Python3.4?

def get(s, ind):
    return len(s)>ind and s[ind] or 0
user2864740
  • 60,010
  • 15
  • 145
  • 220

2 Answers2

2

No, no such built-in method exists for lists. It is trivial to find out if a list index is valid, so no function is needed. You could just put the code in your function (or the even more readable s[ind] if ind < len(s) else 0) directly into the two or three places it's needed, and it would be perfectly understandable.

You can also use the fact that slicing a list always succeeds, take a one-item slice, make an iterator of that, and try to get the next value from the iterator. Then you can specify the default value on the next() call.

next(iter(s[ind:ind+1]), 0)

But this is going to be both slower and less clear than the if construction.

Of course, both your code and mine assume ind is always positive...

If you do want to write a function, you could make it a method of a list subclass.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

There is no methid like get for lists but you could use itertools.islice and next with a default value of 0:

from itertools import islice
def get(s, ind):
    return next(islice(s, ind, ind + 1), 0)

In your code using and s[ind] will return the default 0 if the value at ind is any falsey value like 0, None, False etc.. which may not be what you want.

If you want to return a default for falsey values and to handle negative indexes you can use abs:

def get(s, ind):
    return s[ind] or 0 if len(s) > abs(ind) else 0
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321