generalissimo
generalissimo

Reputation: 21

Loop through one list to see if any usernames corresponds to other list Python

So if a list called new_users is to be looped through and check if any names corresponds to an other list called current_user, how would one go about this task? Additionally .append those new users to the current list.

import time, sys
c_users = ['admin', 'eric', 'eon', 'joseph', 'anton', 'oscar', 'pontus']
n_users = ['joseph', 'eon', 'yasmina', 'jeremiah', 'mugabe']
actually_new_users = list(set(n_users) - set(c_users))
c_users = list(set(c_users).union(set(n_users)))

if not c_users:
      print("List is empty")

for user in c_users:
        print ("Hello, " + c_users [0]+"." + " Do you want a status report?")
        statusr=str(input("Y/N: "))
        if  statusr == "Y" or "y":
            print("The status report is being drafted")
            time.sleep(0.5)
            sys.stdout.write(".")
            time.sleep(1)
            sys.stdout.write(".")
            time.sleep(1)
            sys.stdout.write(".")
            time.sleep(2)
            sys.stdout.flush()
            sys.stdout.flush()
            sys.stdout.flush()
            print("\n")

        elif statusr == "N" or "n":
            print("No status report today, OK.")
        else:
            print("error")
        time.sleep(10)
        print(actually_new_users)
        ##print ("Hello, " + str(c_users))
        ##time.sleep(0.5)
        ##print ("Hello, " + c_users [2])
        ##time.sleep(0.5)
        ##print ("Hello, " + c_users [3])
        ##time.sleep(0.5)
        ##print ("Hello, " + c_users [4])
        break

Upvotes: 1

Views: 209

Answers (1)

Nick Chapman
Nick Chapman

Reputation: 4634

As noted by someone in a comment, a list isn't the most appropriate data structure to store this information in. When you want to make sure that members of one collection aren't present in another collection, you should use a set which will enforce this.

If you are insistent upon having lists then the easiest thing to do is

current_users = ["bob", "sally"]
new_users = ["harry",  "sally"]
current_users = list(set(current_users).union(set(new_users)))
print(current_users)

>>> ['bob', 'sally', 'harry']

Here .union() is being used to update the current_users with the users in new_users that are actually new. If you want to know which users in new_users are already in current_users then you can use .intersection() like so

actually_new_users = list(set(new_users) - set(current_users))
print(actually_new_users)

>>> ['harry']

This is somewhat inefficient because it will result in a lot of copying, BUT it's still likely better than an O(n^2) comparison between two lists*.

*Depending on the size of the lists.

Upvotes: 3

Related Questions