I have a list of lists and inside every list, I have to check if the second element is "daemon", so I wrote a code to that like this:
### code 1
def chech_for_count(my_list: list):
counter_of = 0
for item in my_list:
if item[1].lower() == "daemon":
counter_of = 1
return counter_of
and the task was achieved well but came to my mind I could also make that done using list comprehension which I think it's more pythonic.
### code 2
def chech_for_count(my_list: list):
return len([item for item in my_list if item[1].lower() == "daemon"])
also, the code did what must be done successfully, my question is which one uses less memory and time?
I did a little test with time.time()
and the results varied from one test to another like below:
| Test number|Using list comprehension|Using normal for-loop |
|------------|------------------------|-----------------------|
| First | 0.2046670913696289 | 0.18691778182983398 |
| Second | 0.11920547485351562 | 0.20410394668579102 |
| Third | 0.09914922714233398 | 0.1051473617553711 |
| Forth | 0.10482406616210938 | 0.1894378662109375 |
| Sum | 0.52784585952758788 | 0.6856069564819336 |
The reason behind my question because I doubt if these numbers are real because I think some tests were slower because of CPU usage or something related to the hardware if not, based on these results can we say list comprehension has a better performance?
CodePudding user response:
As stated in the comments you can use sum()
:
my_list = [[1, "xxx"], [2, "deamon"], [3, "deamon"]]
print(sum(l[1] == "deamon" for l in my_list))
Prints:
2
EDIT: Case-insensitive version:
my_list = [[1, "xxx"], [2, "DEAMON"], [3, "deamon"]]
print(sum(l[1].lower() == "deamon" for l in my_list))
Prints:
2