Python Forum

Full Version: readinto a bytearray slice
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why does this work,
>>>> import os
>>>> FILENAME="sample.txt"
>>>> f = open(FILENAME, 'rb')
>>>> data = bytearray(os.path.getsize(FILENAME))
>>>> f.readinto(data)
12
>>>> data
bytearray(b'abc def\ngeh\n')
But this doesn't?
>>>> f = open(FILENAME, 'rb')
>>>> data = bytearray(os.path.getsize(FILENAME))
>>>> f.readinto(data[0:])
12
>>>> data
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
When you slice, you make a copy of the data. So you pass a brand new list to which you have no reference; that's the list that gets modified. If you create a new variable with the slice and pass that new variable, you'll see that it gets modified and that the list from which it was sliced was not changed. In fact, using [:] is a common idiom for a shallow copy.
Thank you.  So then, why does this work?


>>>> data = bytearray(b'abcdef')
>>>> data[0:1] = b'g'
>>>> data
bytearray(b'gbcdef')

I'll answer my own question. Because this is assignment, where as the first example is passing a slice into a function. It's treated differently. Not a copy when assigning. See http://stackoverflow.com/questions/10623...list-slice
Right, one is a regular slice and the other a slice assignment.