Question

Is it possible to "clear" out a (nested) list in python while maintaining the "structure". I mean that if the input it is

[1,3,4,[5,2,[4,3],3],6,[7,8],9]

The output would be

[0,0,0,[0,0,[0,0],0],0,[0,0],0]

Where the actual structure of the list is maintained and just the values are reset.

Context: There actually isn't any, this question just came to mind and I was wondering if it can be done. .

Was it helpful?

Solution

Here is an implementation that makes use of the duck typing principle:

In [5]: def clear(seq):
   ...:     for i, item in enumerate(seq):
   ...:         try:
   ...:             clear(item)
   ...:         except TypeError:
   ...:             try:
   ...:                 seq[i] = 0
   ...:             except IndexError, KeyError:
   ...:                 pass
   ...:             

In [6]: s = [1,3,4,[5,2,[4,3],3],6,[7,8],9]

In [9]: clear(s)

In [10]: s
Out[10]: [0, 0, 0, [0, 0, [0, 0], 0], 0, [0, 0], 0]

The advantage to this is that you aren't restricted to structures/values that are ints or lists. This function will 'zero' out any mutable structure which supports indexing.

OTHER TIPS

>>> l = [1,3,4,[5,2,[4,3],3],6,[7,8],9]
>>> def reset(lst):
...     return [reset(e) if isinstance(e, list) else 0 for e in lst]
...
>>> l = reset(l)
>>> l
[0, 0, 0, [0, 0, [0, 0], 0], 0, [0, 0], 0]

I got this to work using recursion, although it is a bit primitive.

Note: ints and lists only but can be any random nesting. Works for all

def set_zero(lst):
    for i,element in enumerate(lst):
        if type(element) != list: lst[i]=0
        else: set_zero(element)

>>> a = [1,3,4,[5,2,[4,3],3],6,[7,8],9]
>>> set_zero(a)
>>> print(a)
[0,0,0,[0,0,[0,0],0],0,[0,0],0]

Nice question by the way!

I was able to find another method, which is basically cheating but it works.
Also, it is a one-liner!!

def set_zero(lst):
    return eval(''.join(str(0) if x.isdigit() else str(x) for x in str(lst)))

>>> a = [1,3,4,[5,2,[4,3],3],6,[7,8],9]
>>> a = set_zero(a)
>>> print(a)
[0,0,0,[0,0,[0,0],0],0,[0,0],0]

Downside: It is 3 / 4 X slower than my previous suggestion.

Method 1: ~0.000035 s
Method 2: ~0.000120 s

I posted it as a different answer since it is a completely different concept. I can merge it back into my first answer if you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top