Test a list

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Mar 20 14:40:36 EDT 2013


On Wed, 20 Mar 2013 11:15:27 -0700, Ana Dionísio wrote:

> t= [3,5,6,7,10,14,17,21]
> 
> Basically I want to print Test 1 when i is equal to an element of the
> list "t" and print Test 2 when i is not equal:

Wouldn't it make more sense to print "Equal" and "Not equal"?

If all you want to do is check whether some value i can be found in the 
list, you can do this:

if i in t:
    print "Found"
else:
    print "Not found"



If you want to find the index of where a value is found, use the index 
method:

x = 10
t.index(x)  # returns 4



> while i<=25: 
>     if i==t[]:
>        print "Test1"
>     else:
>        print "Test2"
> 
> What is missing here for this script work?

Lots of things. What's i? Does it ever change, or is it a constant? What 
are you comparing it to?


Taking a wild guess at what you mean, you could try this:


for i in range(25):
    print i, "found" if i in t else "not found"



Does this help?


-- 
Steven



More information about the Python-list mailing list