slicing to prevent list index out of range
Say you're writing a function to get a username, based on an ID. However the IDs could be out of bounds. The standard way of doing so would be:
1def get_name(user_id): 2 names = 'john mike mo'.split() 3 return ('', names[user_id])[user_id < len(user_id)]
Despite using a ternary, it still looks pretty cumbersome.
As a remedy, here's a little python trick: list slicing is forgiving when the list index is out of range.
1def get_name(user_id): 2 names = 'john mike mo'.split() 3 return names[user_id:user_id+1]
This change has two effects:
- returns a list with 1 item if the list index is in range
- returns an empty list if the list index is out of range
1In : get_name(0) 2Out: ['john'] 3 4In : get_name(10) 5Out: 
You may now be wondering why we're returning a list when we want a string. Returning a list can be very useful if the calling code is working with lists.
return a list with 0 or 1 items