Reputation: 18109
I want to do like all all()
like comparison to test if my substring is in every element in the list.
Some dummy data:
let my_list = ['~/.tmp/myproject/filea', '~/.tmp/myproject/fileb']
I want to test if .tmp/myproject/
is in every item in this list.
Upvotes: 1
Views: 94
Reputation: 180441
Some timings show exactly why you should use a generator expression:
In [25]: l = ["foobar" for _ in range(100000)]
In [26]: l = ["foobar" for _ in range(100000)]
In [27]: l = ["doh"] + l
In [28]: timeit all("foo" in s for s in l)
1000000 loops, best of 3: 541 ns per loop
In [29]: timeit all(["foo" in s for s in l])
100 loops, best of 3: 6.49 ms per loop
There are some nice example of how to use generators and their advantages here wiki.python.org/moin/Generators
I think a good rule of thumb is if you only plan on using the set of elements generated once or the data is too large to fit in memory use a generator expression. If you want to use the elements again and the size is practical then store them in a list.
Upvotes: 2
Reputation: 18109
all(['mysubstring' in item for item in my_list])
List comprehension is perhapse the best way to do this kind of check, and best of all you can still use all
!
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
Type "help", "copyright", "credits" or "license" for more information.
>>> my_list = ['~/.tmp/myproject/filea', '~/.tmp/myproject/fileb']
>>> my_list
['~/.tmp/myproject/filea', '~/.tmp/myproject/fileb']
>>> [item for item in my_list]
['~/.tmp/myproject/filea', '~/.tmp/myproject/fileb']
>>> ['/.tmp/myproject/' in item for item in my_list]
[True, True]
>>> all(['/.tmp/myproject/' in item for item in my_list])
True
Upvotes: 3