I know I can do a try/except or if/else and set a default based on the error or else clause, but I was just wondering if there was a one liner that could do it like getattr can.
            Asked
            
        
        
            Active
            
        
            Viewed 1,700 times
        
    0
            
            
         
    
    
        13steinj
        
- 427
- 2
- 9
- 16
- 
                    a related question: http://stackoverflow.com/questions/5125619/why-list-doesnt-have-safe-get-method-like-dictionary – newtover Nov 21 '15 at 21:47
1 Answers
6
            The good: just def a helper function
def my_getitem(container, i, default=None):
    try:
        return container[i]
    except IndexError:
        return default
The bad: you can one-liner the conditional version
item = container[i] if i < len(container) else default
The ugly: these are hacks, don't use.
item = (container[i:] + [default])[0]
item, = container[i:i+1] or [default]
item = container[i] if container[i:] else default
item = dict(enumerate(container)).get(i, default)
item = next(iter(container[i:i+1]), default)
 
    
    
        wim
        
- 338,267
- 99
- 616
- 750
- 
                    
- 
                    I actually kind of like the third hack, as long as you can assume `i` is non-negative. – chepner Nov 21 '15 at 21:59