0

I'm trying to change the value of the list that i put as argument in the function.

this is the code:

def shuffle(xs,n=1):
if xs: #if list isn't empty
    if n>0:
        #gets the index of the middle of the list 
        sizel=len(xs)
        midindex=int((sizel-1)/2) 
        for times in range(n):
            xs=interleave(xs[0:midindex],xs[midindex:sizel])
return None

The interleave code returns a list with the values of both lists mixed up.

However when i run:

t=[1,2,3,4,5,6,7]  
shuffle(t,n=2)
print t

The list t didn't changed it's order. The function needs to return None so i can jst use t=shuffle(t,n). There's anyway i can do this?

3
  • "The function needs to return None so i can jst use t=shuffle(t,n)." - that doesn't make any sense. Why don't you return xs at the end of your shuffle function, and then do t = shuffle(t, n)? Commented Nov 2, 2013 at 23:06
  • 1
    Why must it return None? (which incidently, it does by default when you omit the return statement) Commented Nov 2, 2013 at 23:08
  • I explained in the comment of the first answer. Thanks for the help Commented Nov 2, 2013 at 23:11

2 Answers 2

2

Your problem is right here:

xs=interleave(xs[0:midindex],xs[midindex:sizel])

You're making slices of the list to pass to your interleave() function. These are essentially copies of part of the list. There's no way that what comes back from the function can be anything than a different list from xs.

Fortunately, you can just reassign the new list you get back into the original list. That is, keep xs pointing to the same list, but replace all the items in it with what you get back from the interleave() function.

xs[:]=interleave(xs[0:midindex],xs[midindex:sizel])

This is called a slice assignment. Since xs remains the same list that was passed in, all references to the list outside the function will also see the changes.

Sign up to request clarification or add additional context in comments.

Comments

2

xs is a reference local to the function, and is independant of t. When you reassign xs, t still points to the original list.

Since you must not return anything from the function, a workaround is to keep a reference to the original list and repopulate it using slice assignment:

orig_xs = xs
# do stuff here
orig_xs[:] = xs

2 Comments

So there's no way i can change t within the function?
In the assigments specifically says that the function should return None. When i searched this nline i saw that lists are mutable so i should be able to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.