r/Python • • Feb 28 '13

What's the one code snippet/python trick/etc did you wish you knew when you learned python?

I think this is cool:

import this

259 Upvotes

307 comments sorted by

View all comments

Show parent comments

4

u/VictoryTree Feb 28 '13

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

2

u/jcampbelly Feb 28 '13 edited Feb 28 '13

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.