Case-insensitive comparison of lists

Question:

I want to make a code that to see if each new username has already been used in a website.

I have this code:

current_users = ['Rachel', 'Ross', 'Chandler', 'Joey', 'Monica']

new_users = ['Janice', 'Ben', 'Phoebe', 'JOEY']

for new_user in new_users:
    if new_user in current_users:
    print (f'The username {new_user} is alreay in use. You need to enter a new username')

else:
    print (f'The username {new_user} is avaliable')

And this outputs:

  • The username Janice is avaliable
  • The username Ben is avaliable
  • The username Phoebe is avaliable
  • The username JOEY is avaliable

For "JOEY" the message to be printed was supposed to be this: "The username JOEY is alreay in use. You need to enter a new username".

How can I lowercase (or uppercase) the lists to make this code case-insensitive?

Asked By: DR8

||

Answers:

You should create a set that contains all of the lowercased names. Then, to check whether a name can be used, look up the lowercased version of the name in the set:

names_in_use = {name.lower() for name in current_users}

for new_user in new_users:
    if new_user.lower() in names_in_use:
        print (f'The username {new_user} is already in use. You need to enter a new username')
    else:
        print (f'The username {new_user} is avaliable')

This outputs:

The username Janice is avaliable
The username Ben is avaliable
The username Phoebe is avaliable
The username JOEY is already in use. You need to enter a new username
Answered By: BrokenBenchmark