slicing to prevent list index out of range

Go Back home

python list slicing
enumerate
string formatting

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:

1 In [2]: get_name(0)
2 Out[2]: ['john']
3 
4 In [3]: get_name(10)
5 Out[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