Check if a key exists in a Python list

Question:

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.

Asked By: fedorqui

||

Answers:

Use in operator:

>>> mylist=["important", "comment"]
>>> "comment" in mylist
True

Ah! Missed the part where you said, you just want "comment" to be the 2nd element. For that you can use:

len(mylist) == 2 and mylist[1] == "comment"
Answered By: Rohit Jain

What about:

len(mylist) == 2 and mylist[1] == "comment"

For example:

>>> mylist = ["important", "comment"]
>>> c = len(mylist) == 2 and mylist[1] == "comment"
>>> c
True
>>>
>>> mylist = ["important"]
>>> c = len(mylist) == 2 and mylist[1] == "comment"
>>> c
False
Answered By: arshajii

You can use the in operator:

'comment' in mylist

or, if the position is important, use a slice:

mylist[1:] == ['comment']

The latter works for lists that are size one, two or longer, and only is True if the list is length 2 and the second element is equal to 'comment':

>>> test = lambda L: L[1:] == ['comment']
>>> test(['important'])
False
>>> test(['important', 'comment'])
True
>>> test(['important', 'comment', 'bar'])
False
Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.