'How to create a list in python where a member of 1 list is matched to a member of another list?

I am creating a simple login/sign up code, and I have a list called usernames and another one called passwords, how do I make a username match a password and to login the password entered must match the username and can't be another random password in the same list?



Solution 1:[1]

you could use a dictionnary ?

log = {"username":"password", "username2": "password2"}
print("password" == log["username"])

or maybe

username = ["user1", "user2"]
password = ["password1", "pw2"]
user = "user1"
pw = "password1"
print(password[username.index(user)] == pw)

Hope it will help you :)

Solution 2:[2]

Are you looking for a dictionary?

password_db = {
  "user_1": "secret123",
  "user_2": "password123",
  "user_3": "hallo123",
}

# OR if they come from lists:
users = ['user_1', 'user_2', 'user_3']
passwords = ['secret123', 'password123', 'hallo123']
password_db = dict(zip(users, passwords))

print("Enter username:")
entered_username = input()

print("Enter password:")
entered_password = input()

if entered_username in password_db and password_db[entered_username] == entered_password:
  print("Successful login!")
else:
  print("Wrong username or password!")

Solution 3:[3]

If you really want to use a list

ussr = ['u1', 'u2', 'u3']
password = ['nothing', 'good', 'bad']
for index, item in enumerate(ussr):
   if entered_username == item:
      if entered_password == password[index]:
         print("login successful")
      else:
         print("incorrect password")

If you don't know enumerator basically it is as same as this code:-

for index in len(ussr):
  if entered_username == ussr[index]:
    if entered_password == password[index]:
       print("login successful")
    else:
       print("incorrect password")

Enumerator takes a list and returns 2 arguments, 1st one is current index loop's going through second the item in that index (list[index]).

You can make changes of your own. Still a better way, as mentioned in above answers is dictionary.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 magimix
Solution 2
Solution 3