-3

instead of my code printing each element in the list on a separate line only the first element is printed. (1, 3, 4). The for loop doesn't seem to be working when in the function but when not in it works fine why is this and how can I fix it?

item_1 = [1, 2, 3]
item_2 = [1, 3, 4]
item_3 = [2]
item_4 = [3, 4]
item_5 = [5]

def recommend(item):
    item_list = [item_1, item_2, item_3, item_4, item_5]
    item_list.remove(item)
    for items in item_list:
        return(items)

print(recommend(item_1))
  • The description of the problem is not clear and confusing. Please consider to reorganize your words. – Frank Mar 06 '21 at 14:27
  • `return` will stop the loop. Try `yield` instead... Read the docs and do some tutorials – FraggaMuffin Mar 06 '21 at 14:27
  • Please show expected output. – Malo Mar 06 '21 at 14:34
  • *"The `for` loop doesn't seem to be working"* because at beginning when `items` assigned to `item_2` from `item_list`, `return(items)` is executed directly, the function returns `item_2`, so only this element will be printed. Suggest you to read [Python tutorial](https://docs.python.org/3/tutorial/) to know more about basics firstly. – rustyhu Mar 06 '21 at 14:35

2 Answers2

0

You shouldn't return in a loop.

"Using a return inside of a loop will break it and exit the function even if the iteration is still not finished." https://stackoverflow.com/a/44564729/13105480

Instead you can print in a loop.

item_1 = [1, 2, 3]
item_2 = [1, 3, 4]
item_3 = [2]
item_4 = [3, 4]
item_5 = [5]

def recommend(item):
    item_list = [item_1, item_2, item_3, item_4, item_5]
    item_list.remove(item)
    for items in item_list:
        print(items)
    # return(items)

recommend(item_1)
DeTom
  • 96
  • 1
  • 8
0

As frank said, this question is confusing, but from what I understand the function is not returning what you want it to return. And going off of what FraggaMuffin Said about yield, this code should work with what you are trying to do.

item_1 = [1, 2, 3]
item_2 = [1, 3, 4]
item_3 = [2]
item_4 = [3, 4]
item_5 = [5]

def recommend(item):
    item_list = [item_1, item_2, item_3, item_4, item_5]
    item_list.remove(item)
    for items in item_list:
        yield(items)

for y in recommend(item_1):
    print(y)

The first example about yield in this link was simple and should help you understand it: https://www.educba.com/python-yield/

cigien
  • 57,834
  • 11
  • 73
  • 112
CodeAltF4
  • 1
  • 3