Aba Falafel
Aba Falafel

Reputation: 23

changing the value of a list with a function

I have a pre defined list which I want to be a "new" list when the function ends.

for example

x = [4, 5, 6]
y = [1, 2, 3]

What I want is for this function:

extend_list_x(x, y)

to make this

x = [1, 2, 3, 4, 5, 6]

I have tried returning joined_list, but I cannot change the value of x

x = [4, 5, 6]
y = [1, 2, 3]

def extend_list_x(x, y):
    joined_list = [*y, *x]
    global x 
    x = joined_list
    return x

extend_list_x(x, y)

at the moment this is my problem

SyntaxError: name 'x' is parameter and global

Upvotes: 2

Views: 119

Answers (3)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

  • First, avoid global in functions at all costs. Functions have parameters. Use them (and possibly return values)
  • Then, choose between returning a new list or modifying the first one:

this changes x in-place thanks to slice notation in the left hand:

def extend_list_x(x, y):
    x[:] = y+x

or even better, not assigning x fully but reusing previous x value using partial slice assignment. Just tell python to put the right hand contents before index 0 (previous elements will be shifted since the target length is < len(y) because it's 0):

def extend_list_x(x, y):
    x[:0] = y

call like this:

extend_list_x(x,y)

this one creates a new list and returns it, leaving x unchanged

def extend_list_x(x, y):
    return y+x

call like this:

x = extend_list_x(x,y)

Upvotes: 1

Eduardo Santos
Eduardo Santos

Reputation: 1

If you want to create a new list you can simply use the addition operator:

def joiner(x,y):
    return x+y

If you want to keep the same list then you can use the list extend() method:

def joiner(x,y):
    return x.extend(y)

Upvotes: 0

B. M.
B. M.

Reputation: 18628

Since x is mutable, you don't need to use global, which is bad ;) .

def prepend(x,y):
    z=y+x # construct the final result and store it in a local variable
    x.clear() # global x is now []
    x.extend(z) # "copy" z in x

will do the job.

Upvotes: 0

Related Questions