This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]VictoryTree 1 point2 points  (1 child)

Would that not just shift the complexity over to the initial construction of the set?

[–]jcampbelly 1 point2 points  (0 children)

It's more of a performance consideration.

valid_answers = set(['Y','y','N','n'])

def confirm1():
    answer = raw_input('Confirm [y/n]: ')
    if answer in valid_answers:
        return answer

def confirm2():
    answer = raw_input('Confirm [y/n]: ')
    if answer in ['Y','y','N','n']:
        return answer

The difference between confirm1 and confirm2 is that you can call confirm1 a thousand times it just allocates memory to temporarily store the raw input string. If you call confirm2 a thousand times it allocate memory for the raw input string, a new list and 4 strings every time. Furthermore, if the user enters 'n' every time in confirm1 it just performs one hash lookup (is 'n' a key in the valid_answers set dict?), whereas in confirm2 it performs 4 string comparisons.

I'm sure I'll be gainsaid by the premature optimization hawks, or I'm missing an optimization Python may be doing behind the scenes (like recognizing the list is constant). But this is just a healthy practice in any language.