Question

In my example code below, I want to produce an indication of whether a predefined list of numbers either matches or does not match an iterable that I'm looping through. This is a simplified example of my problem.

Unfortunately my code below does not do what I'm expecting, and probably I'm missing something simple. In my real application this is done with extremely large 1 dimensional arrays with varied output, but this demonstrates it in a simple text way that is easy to reproduce.

Maybe I should also add that I'm using Python 2.7.5.

match = [1, 3, 4]
volumes=10

def vector_covariates(match, volumes):
    for i in range(volumes):
        if i == match:
            print "[*]"
        else:
            print "[ ]" 

vector_covariates(match, volumes)

When run, it outputs:

 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ] 

Whereas the "correct" output should be

 [*]
 [ ]
 [*]
 [*]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
Was it helpful?

Solution

Use in not ==:

if i in match:

As it is, you're checking the value of i (a number) to a list, and those two are not going to be the same!

OTHER TIPS

i is a int value, while match is a list. They will never equal to each other.

use in instead of == like this:

if i in match:
    print "[*]"

You're comparing the integer i against the list match. Of course they're not equal. Try using in.

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