If you want to test if some particular items are in a list, you can use ‘in’ or ‘not in’ keywords in Python.
Consider that we have a list containing names of 6 student candidates, then we can test if ‘Bob’ or ‘White’ are in the list.
#create 2 lists, one for students, one for candidates
candidates = ['Jenny', 'Marita', 'Gunnhild', 'Bob', 'Kari','Bjorn']
students = ['Marita','Bob']
#for loop, check if each student in the candidate list
for student in students:
if student in candidates:
print("Hi " + student.title() + ", Congratulation, you are in the list.")
else:
print("Hi " + student.title() + ", Sorry, you are not in the list.")
#output
Hi Marita, Congratulation, you are in the list.
Hi Bob, Congratulation, you are in the list.
Sometimes you can also test whether some items are not in the list, then they simple way could be with keyword ‘not in’. Consider following example, where we want to test whether some usernames (case insensitive) have been used in the current system. If not, then we add new user in the list.
#create two list, one for accepted users, and one for new users to verify
acceptusers = ['sh746', 'seagul', 'europe', 'hongkong', 'list1', 'panties','bra']
newusers= ['Hongkong','Kingston','Zolo']
#for loop to check each new user(lower case), if not in the accept user list,
#add it into the accepted user list, otherwise, print a message
for newuser in newusers:
if newuser.lower() not in acceptusers:
acceptusers.append(newuser.lower())
else:
print("Hi " + newuser + ", Sorry, please select another name.")
#output
Hi Hongkong, Sorry, please select another name.
#print all the accepted users
for user in acceptusers:
print(user)
#output
sh746
seagul
europe
hongkong
list1
panties
bra
kingston
zolo
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…