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.
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list. count() function.
Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With