How to check case insensitive strings in two lists in Python

Viewed 92

I had to compare two lists and whether the string in the new_users is already available in an existing list then the system should highlight it. I have written following code and it worked. Would you appreciate it if anyone can share an even better way to do the same?

    current_users = ["john", "Cindy", "Peter", "Tesla", "Briteny"]
    new_users = ["JOHN", "Cindy", "Nomy", "Tesla", "Tina"]
    i = 0
    for new_user in new_users:
        if new_user.lower() == current_users [i].lower():
            print ("The user name is already taken")
        else:
            print ("The user name is available")
        i += 1
3 Answers

There is a better and pythonic way to get available username list:

availableUsers = list(set([x.lower() for x in current_users])-set([y.lower() for y in new_users]))
  • Make all elements lower using list comprehension, Set both lists (Remove duplicates) and substract them and convert back to list
  • To get number of available use len(availableUsers)

Unavailable ones with:

unavailableUsers = list(set([x.lower() for x in new_users])&set([y.lower() for y in current_users]))

You can simply cast your lists into sets because will be easy compare them likewise to find intersection, symmetric difference, difference, union, etc.

Here is an example

current_users = ["john", "Cindy", "Peter", "Tesla", "Briteny"]
new_users = ["JOHN", "Cindy", "Nomy", "Tesla", "Tina"]

available_users = list(set(map(lambda x: x.lower(), current_users)) - set(map(lambda x: x.lower(), new_users)))
taken_users = list(set(map(lambda x: x.lower(), current_users)) & set(map(lambda x: x.lower(), new_users)))

print(available_users)
print(taken_users)

Then

for i in taken_users:
     print(f'username {i} is already taken')

or

for i in available_users:
     print(f'username {i} is available')

output

username cindy is already taken
username tesla is already taken
username john is already taken
...

This is a simple adoption of your code, which simply uses a set for all existing users to check if the new user already exists. In addition, I added the user name to the print.

current_users = ["john", "Cindy", "Peter", "Tesla", "Briteny"]
new_users = ["JOHN", "Cindy", "Nomy", "Tesla", "Tina"]


current_users_prepared = {user.lower() for user in current_users}

for new_user in new_users:
    if new_user.lower() in current_users_prepared:
        print ("The user name '{}' is already taken".format(new_user))
    else:
        print ("The user name '{}' is available".format(new_user))
Related