tags:

views:

84

answers:

3

How can I search list(s) where all the elements exactly match what I'm looking for. For instance, I want to verify if the following list consist of 'a', 'b' and 'c', and nothing more or less.

lst=['a', 'b', 'c']

I did this:

if 'a' in lst and 'b' in lst and 'c' in lst:
   #do something

Many thanks in advance.

+1  A: 

This does actually work. Why do you think it doesn't?

Also, are you aware of Python sets? http://docs.python.org/library/sets.html

dkamins
because "d" might be in lst too!
THC4k
Yes, you're right. It works. Actually, I forgot to strip() spaces in string elements.
DGT
+6  A: 

You can sort the lists and then simply compare them: sorted( list_one ) == sorted( list_two ).

Also you can convert both lists to sets and compare them. But be careful, sets eat duplicate items! set( list_one ) == set( list_two ).

Sets can also tell you which items either set is lacking: set(list_one) ^ set(list_two).

Some examples:

>>> sorted("asd") == sorted("dsa")
True
>>> sorted( "asd" ) == sorted( "dsa" )
True
>>> sorted( "asd" ) == sorted( "dsaf" )
False
>>> set( "asd" ) == set( "dasf" )
False
>>> set( "asd" ) == set( "daas" )
True
>>> set( "asd" ) ^ set( "daf" )
set(['s', 'f'])
THC4k
+1 nice example using strings there.
TokenMacGuy
+1  A: 

Using sets is fine for what has been asked: In the first case, the lists are identical, having all the elements, nothing less or more While in the second case it is not and it shows up. You can use this for this purpose.

>>> lst=['a', 'b', 'c']
>>> listtocheck = ['a', 'b', 'c']
>>> s1 = set(lst)
>>> s2 = set(listtocheck)
>>> k = s1 ^ s2
>>> k
set([])
>>> listtocheck = ['a', 'b', 'c', 'd']
>>> s2 = set(listtocheck)
>>> k = s1 ^ s2
>>> k
set(['d'])
>>> 
pyfunc