0

I am trying to use a Gotcha statement to hold a list of variables for comparison. But at the end of my procedure I want to reset this list so that it is blank and the process can be restarted. Here is a simple example of what I want, and what I am actually getting:

def append_to(element, reset, to = []):
    if reset == 'reset':
        to = []
        return
    to.append(element)
    return to

my_list = append_to(12, 'Not reset')
print my_list

my_other_list = append_to(42, 'Not reset')
print my_other_list

append_to(1, 'reset')

my_list = append_to(13, 'Not reset')
print my_list

my_other_list = append_to(43, 'Not reset')
print my_other_list

This is the output:

[12]
[12, 42]
[12, 42, 13]
[12, 42, 13, 43]

Output desired:

[12]
[12, 42]
[13]
[13,43]

How can I go about resetting this list? Thanks

Concarney
  • 21
  • 1
  • 1
  • 4

2 Answers2

1

You'll use del to[:] (or to.clear() on 3.3+). Writing to = [] binds to a local variable.

Using append modifies the object which is pointed to by the local variable; this happens to also be pointed to by the caller, which is why the append is working.

This is exactly the misunderstanding that Python Tutor was made for. Here's a visualization of your code.

Veedrac
  • 58,273
  • 15
  • 112
  • 169
0

to = [] does not affect the original list. It just make the local variable to reference the new list.

Use slice notation or del statement to clear the list in-place.

def append_to(element, reset, to = []):
    if reset == 'reset':
        to[:] = []
        # or  del to[:]
        return
    to.append(element)
    return to
falsetru
  • 357,413
  • 63
  • 732
  • 636