Is the in operator lazy in Python?

If I do this, is called split()for each iteration ?:

a = [word for word in post.split() if len(word) > 10]

Should I do this to improve performance?

s = post.split()
a = [word for word in s if len(word) > 10]
+4
source share
2 answers

The only expression is fine - it post.split()will be called only once.

This is because the loop forin Python iterates through the values โ€‹โ€‹of your object that supports iteration - it does not continue to test any conditional statement that you can see in another language, for example, a loop through an array in C.

, post.split() , for .


"" - , , , . , , post.split(), . . Wiki .

+1

post.split() . , post.split() , , :

>>> post = 'a b c d'
>>> def split_post():
...     print('split_post is called')
...     return post.split()
... 
>>> a = [word for word in split_post() if len(word) > 10]
split_post is called

.

+3

Source: https://habr.com/ru/post/1670850/


All Articles