Given:
A = [['Yes', 'lala', 'No'], ['Yes', 'lala', 'Idontknow'], ['No', 'lala', 'Yes'], ['No', 'lala', 'Idontknow']]
I want to know if ['Yes', X, 'No']
exist within A, where X
is anything I don't care.
I attempted:
valid = False
for n in A:
if n[0] == 'Yes' and n[2] == 'No':
valid = True
I know set()
is useful in this type of situations. But how can this be done? Is this possible? Or is it better for me to stick with my original code?
if you want check for existance you can just
['Yes', 'No'] in A
:for the next case try:
or you can possibly define a little func:
any(i[0]=='Yes' and i[2] == 'No' for i in A*10000)
actually seems to be the 10 times faster than than the conversion itself.Following is how to do it using Set().
The elements of Set should be hashable.. so I have used tuples as Set elements and not lists.
Set doesn't support list, you can convert it into tuple,
and as @IgnacioVazquez-Abrams mentioned, the conversion from list to tuple is O(n), so if you are aware of performance, you need to choose other methods.
Convert your
list
toset
first, because it will improve the look up time fromO(n)
toO(1)
:timeit
comparisions:Edit:
If you're only interested in first and last element:
timeit
comparison withany()
: