return a list with 0 or 1 items

Go Back home

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.

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

Output:

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

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

 1 def get_name(uid):
 2     names = 'john mike mo'.split()
 3     return names[uid-1:uid]
 4 
 5 def get_act(act):
 6     activities = 'game chat'.split()
 7     return activities[act:act+1]
 8 
 9 for 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.