3

Is there any way to modify python list through slice with only one value without memory allocations?

Something like that:

b = range(10)
b[2:5] = 1

The problem here is that about memory. I do not want to allocate new objects, because I work with MicroPython on embedded system and unnecessary allocations will affect performance. So should I use cycle or there is more elegant way?

However, I am not really sure about how memory allocations work in python. I have read that Python is smart and allocates variables in stack as well as in heap depending on their usage. Therefore I can not say if:

b = range(10)
b[2:5] = [1]*3

will create a bit of a work for a garbage collector.

Long Smith
  • 1,339
  • 3
  • 21
  • 40

1 Answers1

0

It was naturally better to ask MicroPython developers about that. So I have done that and revealed many interesting things.

b[2:5] = [1]*3

does allocate new object. Even

for i in range(x, y):
    b[i] = 1

allocates memory by range call. Though I expected that this case is treated individually to optimize code. Especially if we are talking about python for embedded systems.

Therefore I suppose the most efficient way to do that is using while cycle.

x = x1
while x < x2:
    b[x] = 1
    x += 1
Long Smith
  • 1,339
  • 3
  • 21
  • 40
  • Was your discussion with the developers on a public forum and if so can you link to it please? I'm struggling to understand your examples because as far as I can see trying to assign to an element or slice of `b` should fail with a `TypeError`. – nekomatic Jan 26 '17 at 09:57
  • @nekomatik you are right, it raises type error, just read the answer more attentively. Assigning element to a slice explains how I would like to do it. But as far as I can not, I search for another way. – Long Smith Jan 26 '17 at 11:09
  • If `b` is a list not an iterable, e.g. `b = list(range(10))`, then e.g. `b[2:5] = [1]*3` will work. If you want to know how to avoid memory allocations in MicroPython though, the MicroPython forum will be the best place to ask. – nekomatic Jan 26 '17 at 11:30
  • @nekomatic the answer describes why using while cycle is the best way to do that in MicroPython. – Long Smith Jan 26 '17 at 11:49