return a list with 0 or 1 items

🏠

Pre-requisites:

slicing to prevent list index out of range

Returning a list with 1 item may not seem like the most useful thing in the world. But it can actually simplify your logic a lot, especially when the caller is also working with lists.

 1def get_name(uid):
 2    names = 'john mike mo'.split()
 3    return names[uid:uid+1]
 4
 5def get_act(act):
 6    activities = 'game chat'.split()
 7    return activities[act:act+1]
 8
 9for i in range(10):
10    s = ['user'] + get_name(i) + ['joined'] + get_act(i//3) + ['session']
11    print(' '.join(s))

Output:

 1user john joined game session
 2user mike joined game session
 3user mo joined game session
 4user joined chat session
 5user joined chat session
 6user joined chat session
 7user joined session
 8user joined session
 9user joined session
10user joined session

Another interesting trick with slicing, is the ability to ignore the zeroeth item:

 1def get_name(uid):
 2    names = 'john mike mo'.split()
 3    return names[uid-1:uid]
 4
 5def get_act(act):
 6    activities = 'game chat'.split()
 7    return activities[act:act+1]
 8
 9for i in range(10):
10    s = ['user'] + get_name(i) + ['joined'] + get_act(i//3) + ['session']
11    print(' '.join(s))

In this case we ignore uid 0. This is very useful since it's quite frequent for your input to start counting from 1.