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:

1In [2]: get_name(0)
2Out[2]: ['john']
3
4In [3]: get_name(10)
5Out[3]: []

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.

See also:

return a list with 0 or 1 items