Search code examples
pythonlistcomparisonsimplification

Comparing list to list ignoring case in both of them Python 3.7 simplification


I'm learning python as my first language, and I'm working with Python crash course as my first book.

In try it yourself 5-10 section there is a task to create two lists and compare the second one to the first using for loop, to check whether or not the username is in the system (ignoring the case).

current_users = ['ana', 'JohN', 'sweeny', 'Bobcat', 'anthony']
current_users_lower = current_users[:]

for x in range(len(current_users)):
    current_users_lower[x] = current_users_lower[x].lower() #nokope listi un partransforme visus uz lowercase

#print(current_users_lower)

new_users = ['polo', 'joHn', 'lamer', 'johan', 'boBcat']
#new_users = []

if new_users:
    for new_user in new_users:
        if new_user.lower() in current_users_lower:
            print("Usernames are case sensitive - username " + new_user + " is taken, please choose another one and try again!")
        else:
            print("Registration successfull, your username is " + new_user)

else:
    print("No usernames to input")

There must be a more elegant way to compare two lists both in lower case. The way I did it was copy the whole list and convert values to lower, and compare new list to converted list, but it seems like awful lot of useless work. Any tips that point to the right direction of simplification would be greatly appreciated. Works as intended, but is messy in my opinion

output : enter image description here


Solution

  • Your current way to compute the list current_users_lower:

    current_users_lower = current_users[:]
    
    for x in range(len(current_users)):
        current_users_lower[x] = current_users_lower[x].lower() #nokope listi un partransforme visus uz lowercase
    

    Could be just this:

    current_users_lower = set(map(str.lower, current_users))
    

    Note that it creates a set instead of a list, as a set is really what you want (you're not using the order of the list) and makes your ... in current_users_lower check faster (constant time instead of linear time).