-2

i am checking two values inside list using if condition and another string should not be in list in python below is my code but it is giving wrong output

lis = ['a','b','c','d','e','f'] #list values or lis =[]
if ('z' or 'a') and not 'x' in lis :
    print "yes"
else :
    print "no"

and output is

yes 

is there anything wrong?

giveJob
  • 1,500
  • 3
  • 17
  • 29
  • Is this a question or an opinion? Either way, your `if` doesn't do what you think it does. – pstatix Apr 02 '18 at 17:01
  • question how to achieve this requirement i now in java but in python!!! – giveJob Apr 02 '18 at 17:02
  • Output of above code will be `yes` as the `if` condition is `True`. [Among 'z' or 'a', the list has 'a'. and the list does not have any 'x'.] – Atur Apr 02 '18 at 17:02
  • @DanielRoseman : There is an 'and' clause between the two conditions. I agree that first condition is always `True` and second condition is based on the elements of `lis`. Combining both conditions (with give data in second condition) will yield the result as 'yes' . – Atur Apr 02 '18 at 17:19
  • @KeyurPotdar : correct and to the point. – Atur Apr 02 '18 at 17:20
  • 1
    lis = ['a', 'b', 'c', 'd', 'e', 'f'] if ('z' in lis or 'a' in lis) and not 'y' in lis : print('yes') else: print('no') it will meet your requirment enjoyyyyyyyyy –  Apr 02 '18 at 17:25

3 Answers3

1

In your code, the if statement evaluates like this:

  • ('z' or 'a') -> 'z' (which is truthy)
  • not 'x' in lis - > True

So, it becomes if 'z' and True, which is True.

Use this code instead:

lis = ['a', 'b', 'c', 'd', 'e', 'f'] 
if any(item in lis for item in ('z', 'a')) and 'x' not in lis:
    print 'yes'
else:
    print 'no'

This will check if any of the items in the tuple ('z', 'a') are in the list, and whether 'x' isn't.

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
1

('z' or 'a') evaluates to be a truthy value ('z') and hence you get yes as output.

lis = ['a','b','c','d','e','f'] #list values or lis =[]
if 'z' in lis or 'a' in lis and not 'x' in lis :
    print "yes"
else :
    print "no"
bhansa
  • 7,282
  • 3
  • 30
  • 55
-1

In the first condition, you're making a generic statement that is considered true. If you want to see if z or a is in lis, it should look like this:

lis = ['a','b','c','d','e','f'] #list values
if ('z' or 'a') in lis and not 'x' in lis :
    print "yes"
 else :
     print "no"
ndmeiri
  • 4,979
  • 12
  • 37
  • 45
bruckerrlb
  • 185
  • 2
  • 7
  • 1
    if ('z' or 'a') in lis and not 'x' in lis : output is "no" it wrong output please check in – giveJob Apr 02 '18 at 17:06
  • The question was edited after I answered. You originally had if ('z' or 'z') which made me think you were looking for "no" but were getting "yes", that's what I was answering for... – bruckerrlb Apr 02 '18 at 17:33
  • @para m answer is correct out put even list is empty – giveJob Apr 02 '18 at 17:38