educative.io

In the nested for loop example there's a flaw

The loop example as written will result in not only comparing each element with every other element in the list but also comparing each element against itself. This is easily demonstrated by changing one number into the list to 25.

I did a quick and dirty fix, BUT this is made with the assumption that the list contains no matching numbers.

n = 50
num_list = [25, 4, 23, 6, 18, 27, 47]

for n1 in num_list:
for n2 in num_list: # Now we have two iterators
if(n1 != n2): #correction added
if(n1 + n2 == n):
print(n1, n2)


Course: Learn Python 3 from Scratch - Free Interactive Course
Lesson: Nested for Loops - Learn Python 3 from Scratch

Hi @Josh1,
Your suggestion is highly appreciated. The lesson has been updated.
We hope Educative has inspired you to further your learning, and please drop us a note if you have any other questions or concerns. Thank you!
Happy learning :slightly_smiling_face:

1 Like