Question

I wanted to know which condition is better to use for the following code:

Here are my two lists:

Matrix = ['kys_q1a1','kys_q1a2','kys_q1a3','kys_q1a4','kys_q1a5','kys_q1a6']
fixedlist = ['kys_q1a2', 'kys_q1a5']

Option 1:

for i, topmember in enumerate(Matrix):
    for fixedcol in fixedlist:
        if topmember in fixedcol:
            print i

OR

Option 2:

for i, topmember in enumerate(Matrix):
    for fixedcol in fixedlist:
        if topmember == fixedcol:
            print i

I understand that the comparison opertor is matching strings but isn't 'in' doing the same?

Thanks

Was it helpful?

Solution

topmember in fixedcol

tests if the string topmember is contained within fixedcol.

topmember == fixedcol

tests if the string topmember is equal to fixedcol.

So, 'a' in 'ab' would evaluate True. But 'a' == 'ab' would evaluate False.

I wanted to know which condition is better to use.

Since the two variants perform different operations, we cannot answer that. You need to choose the option that does the operation that you require.

Your code could be simplified quite a bit. The second option could be reduced to:

for i, topmember in enumerate(Matrix):
    if topmember in fixedlist:
        print i

You could also use a list comprehension to find the matching indices:

[i for i, x in enumerate(Matrix) if x in fixedlist]

If you just have to print the indices rather than store them in a list you can write it like this:

print '\n'.join([str(i) for i, x in enumerate(Matrix) if x in fixedlist])

It's a matter of taste whether you prefer the dense list comprehension one-liner, or the rather more verbose version above.

OTHER TIPS

Hi in opeartor is used for membership testing and == operator is used for equality testing .

Generally we used in for membership testing in sequence object. And is able to test in dictionary, set, tuple, list, string etc. But it behaves differently based on the object types.

Dictionary:

It check for the key exists.

>>> d = {'key' : 'value'}
>>> 'key' in d
True
>>> 'k' in d
False
>>>

Set:

Under the hood it checks for key is exist, set implementation is same as dictionary with some dummy value.

>>> s = set(range(10))
>>> 1 in s
True
>>>

List and Tuple:

For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.

>>> l = range(10)
>>> 3 in l
True
>>>

String:

checking whether the substring is present inside the string eg. x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1

Use defined data type:

user-defined classes which define the __contains__() method, x in y is true if and only if y.__contains__(x) is true.

class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __contains__(self, arg):
        if arg in self.__dict__.keys():
            return True
        else:
            return False

obj_p = Person('Jeff', 90)

print 'Jeff', 'Jeff' in obj_p
print 'age', 'age' in obj_p
print 'name', 'age' in obj_p

I Hope, you will clear some what is the usage of in.

Lets rewrite your snippet:

>>> Matrix = ['kys_q1a1','kys_q1a2','kys_q1a3','kys_q1a4','kys_q1a5','kys_q1a6']
>>> fixedlist = ['kys_q1a2', 'kys_q1a5']
>>> for i in fixedlist:
...     print i, i in Matrix
...
kys_q1a2 True
kys_q1a5 True
>>>

And finally lets see some of the equality test: ==:

>>> 'a' == 'b'
False
>>> 'a' == 'a'
True
>>> 'a' == 'ab'
False
>>> '' in 'ab'    # empty string is treated as a sub-string for any string
True
>>> '' == 'ab'    # False as they are having different values
False
>>>
>>> 1 == 'ab'
False
>>> 1 == 1
True
>>>

Going with '==' is precise if you want to match exact string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top