0

I am learning programming by myself. In my code, I am practicing nested looping, and I am doing an exercise to see if I can find all matching numbers from a list. However it is returning only the first number, and it is not going through the whole list, Can someone please help? Thanks in advance

  mylist = []

def intersection(lst1, lst2):
  for n in lst1:
    for o in lst2:
      if n == o:
        mylist.append(n)
        return mylist
  • 1
    Your `return` should be at the *end* of the function – costaparas Jan 01 '21 at 23:24
  • I'll suggest to use sets instead, as the accepted response in this [question](https://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches) – miguelps Jan 01 '21 at 23:32

6 Answers6

6

The return statement needs to be unindented such that it is placed at the end of the function and not inside the loop:

def intersection(lst1, lst2):
  mylist = []
  for n in lst1:
    for o in lst2:
      if n == o:
        mylist.append(n)
  return mylist

Before, when it was immediately after mylist.append(n), the function returns the result immediately after that line of code, which is triggered once the first overlapping element is found (ie our answer will only have one element). If we put it at the end of the function instead, it will only return once the algorithm is complete.

I also moved the definition of mylist inside the function, otherwise you'd be overwriting your results if you call the function multiple times.

Also, since you're learning python, I also might look into list comprehensions, which are considered more "pythonic", are more concise, and in many cases execute faster:

def intersection(lst1, lst2):
  return [n for n in lst1 for o in lst2 if n == o]

However, both of the above implementations will have duplicates in the result of an overlapping element appears more than once in either list. For example:

intersection([1,1,2,3], [1,1,2,4])
>>> [1,1,1,1,2]

A better implementation would use python sets and the built in set intersection operator:

def intersection(lst1, lst2):
  return list(set(lst1) & set(lst2))

intersection([1,1,2,3], [1,1,2,4])
>>> [1,2]
Jay Mody
  • 3,727
  • 1
  • 11
  • 27
5

Once you return something in a function, there's no going back to the previous call to retrieve more values. Unindent the return statement:

mylist = []

def intersection(lst1, lst2):
  for n in lst1:
    for o in lst2:
      if n == o:
        mylist.append(n)
  return mylist

You can also use the yield statement:

def intersection(lst1, lst2):
  for n in lst1:
    for o in lst2:
      if n == o:
        yield n

print(list(intersection([1, 2, 3], [2, 3, 4])))

Output:

[2, 3]
Red
  • 26,798
  • 7
  • 36
  • 58
3

Here, the return will be executed directly the first time the code enters the if statement.

1- Just unindent your return myList so that it executes after your loops, not during.

2 - Also, it's a bit strange that you have a global variable that you return in the function. I'd suggest keeping things tidy, and return a fresh new list, that will prevent some potential bugs.


def intersection(lst1, lst2):
  mylist = []
  for n in lst1:
    for o in lst2:
      if n == o:
        mylist.append(n)
  return mylist
Pac0
  • 21,465
  • 8
  • 65
  • 74
3

Look at the return statement, the last line of your code. You are returning from the inner 'for' loop as soon as you find a match; so your code will return and never come back to the 'def intersection(lst1, lst2)' function. Try to work on the issue and see if you can find the mistake.

avio8
  • 82
  • 3
3

You simply need to unindent the return statement so both loops can finish before it returns.

def intersection(lst1, lst2):
    my_list = []
    for n in lst1:
        for o in lst2:
            if n == o:
            my_list.append(n)
    return my_list
Chris
  • 4,009
  • 3
  • 21
  • 52
3

It's because of your return !

def intersection():
    lst1=["1","7","5"]
    lst2 = ["8","7"]
    mylist=[]
    
    for n in lst1:
        for o in lst2:
            if n == o:
                mylist.append(n)
     print(mylist)

intersection()
Garbez François
  • 327
  • 3
  • 13
  • This is a totally different (and less useful) function.. It doesn't have any arguments and doesn't return anything. The issue is best fixed simply by correcting the indentation (un-indenting the `return`), rather than changing how the program works.. – costaparas Jan 01 '21 at 23:32
  • It's exactly the same lol ! i just declare the lists and print instead of return...But still it's the same function, and yes it's an indentation problem – Garbez François Jan 01 '21 at 23:40
  • Its not the *same* function. The original function takes input and (attempts to) return output. This function is less useful - it does the same thing every time its called. – costaparas Jan 01 '21 at 23:42