I was solving a question on Leetcode in which I had to compare in a for loop if each string element was a vowel. Initially I did s[i] == 'a' or s[i] == 'e'
and so on, but this was much slower in comparison to if s[i] in vowels
where vowels was a predefined list. I'm curious as to why the latter is faster considering it has to iterate 5 times in the vowels list, whereas in the former I'm just comparing equality five times.
Asked
Active
Viewed 421 times
0
-
1Does this answer your question? [Why is 'x' in ('x',) faster than 'x' == 'x'?](https://stackoverflow.com/questions/28885132/why-is-x-in-x-faster-than-x-x) – mhhabib Nov 17 '21 at 02:26
-
2Does this answer your question? [Python string search efficiency](https://stackoverflow.com/questions/6963236/python-string-search-efficiency): *"The string `__contain__` method is implemented in C and so noticeably faster."* – Nick is tired Nov 17 '21 at 02:36
-
In addition, `s[i]` will be evaluated twice in the first variant; depending on what kind of object `s` is, that may also take some time – Jiří Baum Nov 17 '21 at 02:37