Reputation: 289555
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.
Upvotes: 31
Views: 106308
Reputation: 129497
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
Upvotes: 17
Reputation: 213223
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"
Upvotes: 20
Reputation: 1121554
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
Upvotes: 49