This code gave me an error, how can I check if a variable is in a list?
TomMarks = [66,54,34,79]
JackMarks = [66,54,34,79]
myList = [TomMarks, JackMarks]
if KateMarks in myList:
print("yes")
else:
print("no")
This code gave me an error, how can I check if a variable is in a list?
TomMarks = [66,54,34,79]
JackMarks = [66,54,34,79]
myList = [TomMarks, JackMarks]
if KateMarks in myList:
print("yes")
else:
print("no")
Python can't check if something is in a list if it doesn't know what that something is in the first place. (In general, you get an error if you try to reference a variable that hasn't been defined yet.)
In your example, even though you define myList = [TomMarks, JackMarks]
, if you print the list, you get this:
[[66, 54, 34, 79], [66, 54, 34, 79]]
If you define KateMarks
beforehand, then yes the code will run perfectly. But if the variable is undefined, the Python won't know what to check for.
You need to define a variable before using it. You are telling compiler "KateMarks" and it doesn't know what it is - how do you suppose it would go about it?
This:
TomMarks = [66,54,34,79]
JackMarks = [66,54,34,79]
myList = [TomMarks, JackMarks]
KateMarks = 1
if KateMarks in myList:
print("yes")
else:
print("no")
works fine and prints "no".
What you probably want is to check if the variable exists first:
if 'KateMarks' in locals():
If your really want to print no
even if KateMarks
is not defined, you can do the following, but it is not a good way of going about it.
TomMarks = [66,54,34,79]
JackMarks = [66,54,34,79]
myList = [TomMarks, JackMarks]
try:
if KateMarks in myList:
print 'yes'
else:
print 'no'
except(NameError):
print 'no'
Python variable names are references to objects. Because KateMarks is not referencing anything Python will raise a NameError exception.
Namespace introspection can be acheived with locals()
or dir()
'KateMarks' in dir()
Instead of lists you can do it by dictionaries, like this:
myList = {'TomMarks':[66,54,34,79], 'JackMarks':[66,54,34,79]}
if 'KateMarks' in myList:
print("yes")
else:
print("no")
Do you mean you're writing some sort of code where you'll get Kate's marks somewhere else in the program, and then check if the marks are in it?
Or actually, on second thought I think the whole list-in-a-list and marks idea is just a distraction... you really mean to ask if you can use a variable name in a similar fashion to a string, right? If that's the case, there's a somewhat not-so-efficient way to do what I think you're trying to do, using dict
:
marks = {} # a Python dictionary
marks["Tom"] = 1234123412512352345
marks["Jack"] = 2394872394857389578935
if "Kate" in marks:
print("Kate is a key in marks.")
else:
print("Kate isn't a key, but at least now we know that we didn't get Kate's marks.")
If variable is undefined you just simply check if it is undefined. No undefined variables can be in any list:
if not 'undefined_variable' in dir():
print "NO WAY!"