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] 
tcatchy
  • 849
  • 1
  • 7
  • 17

3 Answers3

2

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

def my_func(l):
  del l[:]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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.

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • 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. – SethMMorton Nov 01 '13 at 22:36
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()
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180