Modifying an element of a list in a function, question


#1

https://www.codecademy.com/courses/python-beginner-nzzVa/2/3?curriculum_id=4f89dab3d788890003000096

Oops, try again. list_function([1, 1]) returned [3, 11, 7] instead of [1, 4]

I expected it to work, if I print the listfunction it all appears right. When I change the list to a different set of numbers; it prints that list with 3 added to the number indexed on 1. Could someone please give some explanation. I looked at other posts like this one, but don't understand why this will not work.


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

n = [3, 5, 7]
print list_function(n).


#2

Hi @jinx_80,

The function parameter is x, however your function code ignores that variable and accesses the global variable, n, directly instead.


#3

look:

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

n = [3, 5, 7]
print list_function(n)
print list_function([1, 1])

[1, 1] doesn't get correct output? A function which only works for a single list, doesn't follow DRY principles.


#4

Well, thnx! I just needed to change the x to n and it worked indeed. Wonderfull, I didn't get al the code where ppl put "for 1 in range" in the function. I thought it looked to complex, but as a beginner I thought I might be missing stuff :slight_smile:
This was really helpfull!

Regards


#5

do you understand now how function parameters (x) and arguments (n and [1, 1]) work?


#6

I think so, but I'm gonna try several of these lessons a second time to see how far I'll get. Most of the other lessons so far were pretty clear, I just couldn't understand why the code shoul've been longer than what I made. Now it appears it needn't be longer, I just didn't see the x
. I tried the print list_funtion([1,1]) with the x substituted with the n and that worked as well. So I think I understand it now. (Unless you think I don't; as I implied; I'm a coding noob :slight_smile: )


#7

2 posts were split to a new topic: Modifying an element of a list in a function


#8

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