One of the many cool things about Python is that you can often use builtin functions to either get a value from a dictionary (or an object with getattr) or default to a specified value. Unfortunately lists do not provide such a function. The simplest use case would be to get the first value out of any list if it exists and if not simply return None. After fiddling around with a few different implementations, I landed on this one:

def get_at(list, index, default=None):
return list[index] if max(~index, index) < len(list) else default [/code] The above function can be used in order to either return the value at the specified index or a default value if the index doesn't exist: [code language=python] lists = [[], ['Hello world!!!'], range(10)[3:]] for list in lists: print 'list = {}'.format(list) print '- first value: {}'.format(get_at(list, 0)) print '- second value: {}'.format(get_at(list, 1)) print '- last value: {}'.format(get_at(list, -1)) print '- 5th value (defaults to "missing"): {}'.format(get_at(list, 4, 'missing')) print '' [/code] The above code outputs the following: [code language=plain] list = [] - first value: None - second value: None - last value: None - 5th value (defaults to "missing"): missing list = ['Hello world!!!'] - first value: Hello world!!! - second value: None - last value: Hello world!!! - 5th value (defaults to "missing"): missing list = [3, 4, 5, 6, 7, 8, 9] - first value: 3 - second value: 4 - last value: 9 - 5th value (defaults to "missing"): 7 [/code] You may be thinking that there must be another way to do this. There are in fact various other ways to do this. One of them is to use `next(iter(list[index:]), default)` as the return value. The main reason I landed on the solution that uses max() and a ternary statement is because I wanted to minimize the amount of objects created. Using next() along with iter() requires a generator to be created for the sliced list. On the other hand, Python handles all of this pretty efficiently so its possible that the difference between the two solutions is minimal. Either way, now I have a succinct helper function that either gets me a list item or the default value I specify. šŸ˜Ž

Categories: BlogPython

Leave a Reply

Your email address will not be published. Required fields are marked *