patternpythonMinor
Is there a simpler way to make an English-readable list from strings in a tuple?
Viewed 0 times
fromreadableenglishmakewaysimplertuplelisttherestrings
Problem
I looking over some old code, I had written the function below with a C-style for-loop iterating over a count variable. I then fixed it up with new knowledge, but still am suspicious that there is even a better way to do this.
The function should behave like so:
The function I have currently:
The function should behave like so:
>>> join_list(['a'])
'a'
>>> join_list(['a', 'b'])
'a or b'
>>> join_list(['a', 'b', 'c'])
'a, b, or c'The function I have currently:
def join_list(my_list):
length = len(my_list)
if length == 1:
return my_list[0]
elif length == 2:
return ' or '.join(my_list)
else:
head = ', '.join(my_list[:-1])
return head + ', or ' + my_list[-1]Solution
Looks pretty good. The only problem I can see is that you're not doing a check to make sure the list is not empty: if it is, then you'll try to access
Hence, I'd simply add a check up front for
my_list[-1] in the final else clause, which will raise an IndexError.Hence, I'd simply add a check up front for
length == 0 and return '' in that case.Context
StackExchange Code Review Q#41199, answer score: 8
Revisions (0)
No revisions yet.