slicing to prevent list index out of range
python list slicing
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:
1 def get_name(user_id): 2 names = 'john mike mo'.split() 3 return names[user_id] if user_id < len(user_id) else ''
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.
1 def 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
1 In : get_name(0) 2 Out: ['john'] 3 4 In : get_name(10) 5 Out: 
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