1

[SOLVED]

So the code goes like:

>>> a = [1,3,2]
>>> my_func(a)
>>> a == []
True

Where my_func alters the list without returning it. I know how to do this in C with pointers, but really confused over a python solution.

Thanks in advance!!

EDIT: So I am doing a radix sort which has a helper function and the helper function returns the sorted list. I want the main function to alter the original list instead of returning it:

def radix(a):
    base = ...
    temp = radix_helper(a, index, base)
    a[:] = []
    a.extend(temp)

So it would run as:

>>> a = [1,3,4,2]
>>> radix(a)
>>> a
[1,2,3,4] 
2
  • Are you asking why this is allowed to happen, or do you want to know how to write a function that does this? It's not clear. Commented Nov 1, 2013 at 22:34
  • stackoverflow.com/q/9317025 Commented Nov 1, 2013 at 22:35

3 Answers 3

2

Lists are mutable, so all you need to do is mutate the list within the function.

def my_func(l):
  del l[:]
Sign up to request clarification or add additional context in comments.

Comments

1

Python passes parameters by value, but the value of a is a reference to a list object. You can modify that list object in your function:

def my_func(a):
    a.append('foobar')

This can be the cause of unplanned side effects if you forget that you're working directly with the object in question.

1 Comment

No, if you do a = [] inside your function, a now refers to a different object than what was passed to the function. This will not give the effect the OP wants.
0

If the identifier is fixed then you can use the global keyword:

a = [1,2,3]

def my_func():
    global a
    a = []

Otherwise you can modify the argument directly:

a = [1,2,3]

def my_func(a):
    a.clear()

Comments

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.