List-taking and len () versus simple for loop

I have to take a list of words and count all the words in it with a length of 2 or more characters and where the first and last characters are equal.

I came up with two possible solutions:

result = 0
for word in words:
    if len(word) >= 2 and word[0] == word[-1]:
        result += 1
return result

against.

return len([word for word in words if len(word) >= 2 and word[0] == word[-1]])

Which one would be the preferred solution? Or are there any better ones?

+5
source share
5 answers

In your second example, an expression would be better than list-comp if your list is large.

sum(1 for word in words if len(word) >= 2 and word[0] == word[-1])
+14
source

The first, of course, will be the preferred solution in Python.

Do not forget your Zen of Python:

Zen Python, Tim Peters

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

The complex is better than complex.

, .

.

.

.

.

.

.

.

- - .

, .

, .

, .

, .

, .

- - !

, .

+3

, , ( , ).

/:

result = 0
for word in words:
    result += int(len(word) >= 2 and word[0] == word[-1])
return result

int(), , , True 1, . :

return sum(len(word) >= 2 and word[0] == word[-1] for word in words)

len(), , :

len(1 for word in words if len(word) >= 2 and word[0] == word[-1])
+2

.

:

List comprehension , len. .

+1

, :

-, . , , :

def check(word):
    return len(word) >= 2 and word[0] == word[-1]
sum(1 for word in words if check(word))

, ( ) , :

len(filter(check, words))

There itertools.ifilter, but if you use this, you need to use the expression again sum, so it will not become more clear.

The trick sumarises so often that I am surprised that there is no standard library call to count the number of elements in the iterator (if there is, I did not find it). Alternatively, it makes sense if lenit consumes and counts the number of records in the iterator, if it does not __len__, but it is not.

+1
source

All Articles