0

I am having trouble understanding how functions work with nested lists. For example:

def function(x):
   return (i for i in x)

x = function([[99, 0], [0, 99]])
print(list(x))

Gives the result:

[[99, 0], [0, 99]]

However, this code:

def function(x):
   for i in x:
       return i

x = function([[99, 0], [0, 99]])
print(list(x))

Gives:

[99, 0]

Why doesn't the second code print the second component of the list?

teal_sky
  • 29
  • 3
  • 1
    Does this answer your question? [What is the purpose of the return statement?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement) – Jan Christoph Terasa Jun 19 '20 at 05:43

2 Answers2

3

In the second code, the return function is inside the loop. Once your function sees return once, it's over.
In the first code, return is called on the generator inside the parentheses, so everything inside the parentheses is executed when you call the function.

Steve
  • 347
  • 1
  • 4
  • 14
1

In the second code snippet, iteration is happening on the list of lists([[99, 0], [0, 99]]) so when the iteration takes place it will pull the first element of the list that is [99,0] and in next line its encounter return statement that causes the function to stop executing and hand a value back to whatever called it.

Pawanvir singh
  • 373
  • 6
  • 17