Juggle return encounter for loop

How the function returns a list of all elements in the for loop?
what? A little dizzy, then take a look at an example

We look at a simple for loop chestnuts:

for i in range(1,6):
print(i)

-> Output:
. 1
2
. 3
. 4
. 5
our requirements are: return of all elements i

We now put this cycle on the function, we directly call the function to see.

def brucepk():
for i in range(1,6):
return i

brucepk = J ()
Print (J)
so that when invoked, it will return all of the elements? We look at the results:

-> 1
results equal to 1, why? Because once encountered in return for loop will immediately terminate the loop, the first time i met cycling to 1 return immediately stop and return, so when you call the function returns i 1 is the first cycle value when.

I want to return all of the elements of how to do it? On the outer loop is not feasible for it? Let's take a look:

def brucepk():
for i in range(1,6):
pass
return i

brucepk = J ()
Print (J)
here do not cycle for processing, directly pass, pass without doing anything, just play the role of placeholder.
Call the results are as follows:

-> 5
on the outside of the loop, and so the cycle over again assigned to cycle 5, the end of the cycle, it is returned to the caller is 5, this still does not meet our needs.

Solutions
we create a new empty list object when the cycle has not yet started in the for loop with append to all elements added to the object and returns an empty list add list object.

def brucepk():
k=[]
for i in range(1,6):
k.append(i)
return k

brucepk = J ()
Print (J)
so that you can return all elements i in the form of a list.

# Output:
[1, 2, 3, 4, 5]

Published 41 original articles · won praise 7 · views 3669

Guess you like

Origin blog.csdn.net/weixin_43091087/article/details/105072175