deluis
deluis

Reputation: 1

if/else in list comprehension for python

count = 0
users = new_user[count]
[print(f'{users} user name taken'), count +1 if users == current_users else count+1 for users in current_user]

returns an error 

Mind you I am a beginner currently self-studying please explain in a way that someone starting out might understand.

Thank you in advance for helping.

Upvotes: 0

Views: 160

Answers (1)

Arifa Chan
Arifa Chan

Reputation: 1015

Errors caused by:

  • current_users should be current_user
  • print(f'{users} user name taken'), count +1 should be in parentheses

When it get fixed:

  • You might think users in list comprehension is new_user[count], it's actually not.
  • if users == current_users is always False. Even though you change it with in, the output might not as you expected.
  • count = 0, users = new_user[count], and count +1 is unnecessary

A straightforward way would be iterate over new_user and check if its element in current_user then print it:

current_user = ['a', 'b', 'c', 'd', 'e']
new_user = ['b', 'd', 'f', 'g', 'h']

[print(f'{users} user name taken') for users in new_user if users in current_user]

Or normal for loop:

current_user = ['a', 'b', 'c', 'd', 'e']
new_user = ['b', 'd', 'f', 'g', 'h']

for user in new_user:
    if user in current_user:
        print(f'{user} user name taken')

Output:

b user name taken
d user name taken

Upvotes: 1

Related Questions