Ad

How To "convert" From A List-comprehension With Both: For-in & If-in... To "normal" Python3 Code With Loops & Conditions

please don't close this, since i'm a newbie to py3. Help me to "convert" from a list-comprehension with both: for-in & if-in... to "normal" python3 code with loops & conditions:

Why the hassle? Because frankly it will help me understand both of the concepts, since i've just started with py3, it makes me anxious... really badly.

# here is the original code that needs conversion...
friends = ["Wolf", "Frootie", "charlean", "Jenny"]
guests = ["xavier", "Bobbie", "wolf", "Charlean", "ashley"]

friends_lcase = [f.lower() for f in friends]
#guests_lcase = [g.lower() for g in guests]

present_friends = [
  name.title() for name in guests if name.lower() in friends_lcase
]
print(present_friends)



# here below should be the equivalent of
# the above code, which is the issue for me...
# i tried the next but failed, help:

present_friends_2 = []
for i in friends:
    if i.lower() in guests:
      present_friends_2.append(i)
    else:
      present_friends_2.append(0)

print(present_friends_2)
Ad

Answer

Nithin Varghese's answer is almost correct.

friends = ["Wolf", "Frootie", "charlean", "Jenny"]
guests = ["xavier", "Bobbie", "wolf", "Charlean", "ashley"]

#friends_lcase = [f.lower() for f in friends]
friends_lcase = []
for f in friends:
    friends_lcase.append(f.lower()) <--- Change

# present_friends = [
#   name.title() for name in guests if name.lower() in friends_lcase
# ]

present_friends = []
for name in guests:
    if name.lower() in friends_lcase:
        present_friends.append(name.title())


print(present_friends)

Wolf wasn't caught as it was not being converted to lowercase before being added to friends_lcase

Ad
source: stackoverflow.com
Ad