Python Forum
readinto a bytearray slice - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: readinto a bytearray slice (/thread-145.html)



readinto a bytearray slice - bhowerter - Sep-23-2016

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')



RE: readinto a bytearray slice - micseydel - Sep-23-2016

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.


RE: readinto a bytearray slice - bhowerter - Sep-23-2016

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/10623302/how-assignment-works-with-python-list-slice


RE: readinto a bytearray slice - micseydel - Sep-23-2016

Right, one is a regular slice and the other a slice assignment.