Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
iteration stops
#1
quick question:

the following loop
list_nums= [i for i in range(15)]

    for i in range(len(list_nums)):
        if list_nums[i]<9:
            print(list_nums[i])
works as it should since all the numbers from 0 to 8 are printed,
but if I place the same loop into a function:
list_nums= [i for i in range(15)]
def fn():
    for i in range(len(list_nums)):
        if list_nums[i]<9:
            return(list_nums[i])
print(fn())
Only the first number is printed.
As far as I am understanding, the 'return' command interrupts the loop.

How do I make this function work the same way as the loop in the first code?
I am trying not to use any 'print' command inside the function.
Reply
#2
As I see it there are several problems.

- this is not phytonic way. Don't use indices, len etc. Canonical way in Python is to iterate directly over items:

>>> list_ = [1, 3, 5, 9]
>>> for item in list_:
...     if item < 5:
...         print(item)
...
- this function is not reusable as there are no arguments (list_nums is hardcoded)
- there are several ways to achieve desired result (as I understand this is printing elements which are lower than 9):

print(*[item for item in list_nums if item < 9], sep=', '])
--> 0, 1, 2, 3, 4, 5, 6, 7, 8

print(*filter(lambda item: item < 9, list_nums), sep=', ')
--> 0, 1, 2, 3, 4, 5, 6, 7, 8
If needed, separator can be set to newline ('\n').
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Thanks for replying.
However, unfortunately my question has not been answered.
I just need to know how to change my function to make it work like the first for loop I wrote.
I know that there are no arguments, but I just wrote it this way to understand the mechanism.
If there is a way to change the function to make it print those numbers, I'd be happy to learn.
Reply
#4
ok, this should work. See comments

list_nums= [i for i in range(15)] #your line
def fn(ln): #ln will be list_nums but less confusing scope
    output = [] #because you want all the numbers at once
    for i in ln: #proper for loop. Anything with range(len(anything)) there is a better way
        if i<9: 
            output.append(i) #add to list
    return output #this is what you return, not a single value
print(fn(list_nums))
Reply
#5
The 'mechanism' of the Python function is relatively simple: if function returns something, control returns to the function caller. This means that after return function is done. So as in jefsummers example - one must construct whole list first and then return said list at once.

That said one can make generator function and yield instead of returning. This enable yielding one element at the time and doesn't require building list:

>>> nums = [1, 3, 4, 5, 7, 8]
>>> def evens(list_):
...     for item in list_:
...         if item % 2 == 0:
...             yield item
...
>>> print(*evens(nums), sep='\n')
4
8
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020