Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 273
fedorqui 'SO stop harming' Avatar asked Aug 06 '13 15:08

fedorqui 'SO stop harming'


People also ask

How do you check if a value is in a list Python?

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.

How do you check if a dictionary contains a key?

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.


Video Answer


2 Answers

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 
like image 78
Martijn Pieters Avatar answered Oct 03 '22 18:10

Martijn Pieters


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 
like image 38
arshajii Avatar answered Oct 03 '22 19:10

arshajii