Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python slice assignment of generator to list

Tags:

python

list

slice

my_list = [1, 2]

def f():
    print my_list
    yield 11
    print my_list
    yield 22
    print my_list

my_list[:] = f()

print "finally ",
print my_list

output:

[1, 2]
[1, 2]
[1, 2]
finally  [11, 22]

what I expected was:

[1, 2]
[11, 2]
[11, 22]
finally [11, 22]

Someone once told me slice assignment was in place. Obviously not. Is there an elegant way to achieve it?

like image 564
robert king Avatar asked Dec 27 '22 19:12

robert king


1 Answers

Slice assignment is in-place, but the assignment doesn't happen until the entire generator is consumed. It doesn't assign one element at a time to the list. It reads them all and then sticks them all into the list at once.

(Note that it has to do it this way because you can assign a sequence to a slice even if the sequence is a different length than the original slice. You can do, e.g., x[2:3] = [1, 2, 3, 4, 5, 6]. There's no way to do this by replacing one element at a time, because there's no one-to-one mapping between the old slice and the new sequence that's replacing it.)

There isn't a way to achieve what you want by slice assignment, because slice assignment always works in this all-at-once way. You would have to iterate over the list and the generator in parallel and replace individual elements one at a time.

like image 51
BrenBarn Avatar answered Jan 09 '23 15:01

BrenBarn