Modifying an element of a list in a function 10/18


#1

I’m confused about this lesson, or more specifically the use of return. The example given does not use return but still prints the updated list. When I remove return from the code in the editor and run the code, “None” appears in the console. If the premise is the same, modifying an element of a list in a function, why is return needed in the code I am updating?


def list_function(x):
  x[1] = x[1] + 3
  return x

n = [3, 5, 7]
print list_function(n)
print
 
def double_first(n):
  n[0] = n[0] * 2

numbers = [1, 2, 3, 4]
double_first(numbers)
print numbers


#2

Lists, dictionaries, tuples and sets are all data structures that are reference objects meaning they cannot be directly copied.

def double_first(n):
  n[0] = n[0] * 2

numbers = [1, 2, 3, 4]
double_first(numbers)
print numbers

The above change to n is reflected in numbers because that is the actual object that changed. n was just a different name on the same object. It is not an independent copy of numbers.

When a function has not have a return statement, or no return value, None is the value that the caller sees.

>>> def foo():
	pass

>>> print (foo())
None
>>> def foo():
	return

>>> print (foo())
None
>>> 

Like above, if we wish to output the return value, then an explicit return will be needed.


#3

Thank you for the explanation. I don’t quite get it, but I attribute that to my limited knowledge. I’ll keep at it and will use this as a reference point going forward.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.