0

When I use the code:

def Jack():
    global PHand
    if 11 or 24 or 37 or 50 in PHand:
        PHand.remove(11 or 24 or 37 or 50)
        PHand.append("Jack")

I get an error saying list.remove(x) x is not in PHand, my question is, shouldn't the if check prevent this error?

1
  • What are you really trying to do? What's special about those numbers? Commented Feb 2, 2014 at 6:35

3 Answers 3

5

You're basically checking to see whether 11 is true. It's non-zero, so your if always executes. What you want is:

if 11 in PHand or 24 in PHand or 37 in PHand or 50 in Phand:

Of course, your PHand.remove always tries to remove 11 for much the same reason. You can't tell remove to remove any of those (not sure where you got the idea that would even work, it's not in any documentation I've ever seen), so you should structure it so:

if 11 in PHand:
   PHand.remove(11)
   PHand.append("Jack")
if 24 in PHand:
   PHand.remove(24)
   PHand.append("Jack")

... and so on.

Of course you'd be better off refactoring that into a loop or even a function, rather than repeating all that code.

Sign up to request clarification or add additional context in comments.

Comments

5

You need to iterate over each element:

for i in (11, 24, 37, 50):   # assign i to 11, then 24, then 37, then 50
    if i in PHand:           # check each one in PHand
        PHand.remove(i)      # and remove that one
        PHand.append("Jack") # your code
        break                # end the loop. remove this to check all

Otherwise, 11 or 24 or 37 or 50 in PHand outputs 11. Try it!

>>> 11 or 24 or 37 or 50 in PHand
11

Why? the way or works, it checks if the first side is truthy. If it is, it doesn't bother evaluating the rest, since the result couldn't change. If it weren't truthy, it would move on to the next argument, and so on.

And what of the in PHand? That actually gets evaluated first, to just the last number like this:

11 or 24 or 37 or (50 in PHand)

But again, 11 short-circuits all the ors.


Long story short:

or always returns a single value, not all values at once applied to functions repeatedly or however your syntax implies.

Comments

1

Just another way of solving it using filter:

  def Jack():
      T = [11,24,37,50]
      found = filter(lambda x:x in T, PHand)
      if found:
          [PHand.remove(x) for x in found]
          PHand.append('Jack')

  PHand = range(10,55)
  Jack()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.