Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
How to rewrite if-else statements better in python

I have some if-else statement like below, basically it works like charm, but the conditions're changed frequently, it can add more,.... So I think if-else way isn't optimize. That's why I wonder if there are a better solution to reduce code duplicated for that.

name1, name2, name3, name4, name5 =   "David", "Luke", "Kate", "Bobby", "Megan"
sentences = ["Megan is my friend", "Boddy is my friend"]
existed_name = []
for sentence in sentences:
    if name1 in sentence:
        existed_name.append(name1)
    elif name2 in sentence:
        existed_name.append(name2)
    elif name3 in sentence:
        existed_name.append(name3)
    elif name4 in sentence:
        existed_name.append(name4)
    elif name5 in sentence:
        existed_name.append(name5)
    else: 
        existed_name.append('Empty')

Thank you so much for helping me out.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Adding to Abhinav's answer, you can have a flag to see if the name existed or not.

names = ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]

for sentence in sentences:
    existed = False
    for name in names:
        if name in sentence:
            existed_name.append(name)
            existed = True
            break

    if not existed:
        existed_name.append("Empty")        
over 4 years ago · Santiago Trujillo Report

0

You could use a simple nested loop for this if you define all the names in a single list instead of as separate variables.

names = ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]
existing_names = []
for sentence in sentences:
    for name in names:
        if name in sentence:
            existing_names.append(name)
            
print(existing_names)
# ["Megan"]
over 4 years ago · Santiago Trujillo Report

0

If you prefer one liner list comprehension

names =   ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]

existed_name = [name for name in names for sentence in sentences if name in sentence]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!