junkfoodjunkie
junkfoodjunkie

Reputation: 3178

Check all values of tuple in list

I have a list set up like this in Python (via Ren'Py):

[('nc',nc,'test test test'),('nr',nr,'test test test')]

The 'nr' is a string, naturally, and the nr (without the quotes) is an object. The last bit is a string.

Now, what I would like to be able to do, is compare the whole tuple in an if.

Something like this:

if (char,charobj,message) not in list:
    #do stuff

This does not work - it still does stuff regardless. So... how do I compare all of the items to each of the tuples in the list?

Upvotes: 0

Views: 580

Answers (1)

PlikPlok
PlikPlok

Reputation: 110

Hmmm...

I guess that you charobj may be a class you implemented yourself. To allow Python to perform a meaningful equality comparison an not just a blind comparison, you have to overload the default methods for that like :

  • __eq__(self, other)
  • __gt__(self, other)
  • __lt__(self, other)
  • ...

More information there : https://docs.python.org/3/reference/datamodel.html#special-method-names

Anyway, I made some tests and it works fine with literal and built-in types. I am using Python 2.7 on Windows 10 (x64).

nr = 4
nc = 2
list = [('nc',nc,'test test test'),('nr',nr,'test test test')]

if ('nc', 2, 'test test test') in list:
    print('OK')
else:
    print('KO')

actually prints OK.

I tried with not in, it prints KO.

I also tried to replace the literals with variables and it seems to work too.

nr = 4
nc = 2
list = [('nc',nc,'test test test'),('nr',nr,'test test test')]

_nc = 'nc'
_message = 'test test test'
if (_nc, nc, _message) in list:
    print('OK')
else:
    print('KO')

also prints OK.

Hope that helps.

Upvotes: 0

Related Questions