Tuesday, 6 August 2013

Check if a key exists in a Python list

Check if a key exists in a Python list

Suppose I have a list that can have either one or two elements:
mylist=["important", "comment"]
or
mylist=["important"]
Then I want to have a variable to work as a flag depending on this 2nd
value existing or not.
What's the best way to check if the 2nd element exists?
I already did it using len(mylist). If it is 2, it is fine. It works but I
would prefer to know if the 2nd field is exactly "comment" or not.
I then came to this solution:
>>> try:
... c=a.index("comment")
... except ValueError:
... print "no such value"
...
>>> if c:
... print "yeah"
...
yeah
But looks too long. Do you think it can be improved? I am sure it can but
cannot manage to find a proper way from the Python Data Structures
Documentation.

No comments:

Post a Comment