Two questions about speed/efficiency/best practices in Python. Which of the following are ‘better’ (faster, less memory-intensive, etc.):
-
for x in list: #do something to xor
for x in xrange(len(list)): #do something to list[x] -
for string in list_of_strings: for string2 in other_string_list: if string == string2: #do somethingor
import re for string in list_of_strings: if re.match('%s'%(string),other_strings): #or re.search(etc) #do something
Not terribly pressing, I’m mostly just curious. I guess I could get some kind of raw data using timeit() or whatever, but I’d appreciate more depth than just “this one is faster than that one on your computer.”
You can’t really compare these.
is the usual idiom, but whatever you do to
xwon’t affectmylist(unlessxis mutable). If your goal is to modifymylistduring the iteration, thenis almost always bad form. A better way would be to use
But usually, you’re even better off using a list comprehension or a generator expression:
All that depends on your use case.
As for your second question, using a regex for a plain string equality comparison is overkill. Nesting two for loops is horrible, too:
would be a little better, but I’m pretty sure that that can be improved if, again, more is known about your actual use case.