pythonintermediate10 minutes

Refactor Nested Loops to Improve Code Readability and Efficiency

Refactor the given Python function that uses nested loops to find common elements between two lists. Improve its readability and performance without changing its behavior.

Challenge prompt

You are given a function that finds all common elements between two lists by using nested loops. While this approach works, it is not efficient and the code is harder to read. Refactor the function to produce the same result but improve its readability and performance. Do not change the function signature or the output format.

Guidance

  • Aim to reduce the time complexity by avoiding nested loops where possible.
  • Improve code readability by using meaningful variable names and simpler constructs.
  • Keep the output in the same order as the original function.

Hints

  • Consider using Python sets to eliminate the need for nested loops.
  • Remember that converting lists to sets can improve lookup speed drastically.

Starter code

def common_elements(list1, list2):
    result = []
    for i in list1:
        for j in list2:
            if i == j:
                if i not in result:
                    result.append(i)
    return result

Expected output

[2, 4]

Core concepts

refactoringperformance optimizationdata structures (sets and lists)

Challenge a Friend

Send this duel to someone else and see if they can solve it.