rdatacode provide affordable online training course for Python and R programming at fundamental level, click here for more details.

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

You can also watch videos on our YouTube channel for more understanding of Python programming skills.


0 Comments

Leave a Reply

Avatar placeholder