Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
readinto a bytearray slice
#1
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')
Reply
#2
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.
Reply
#3
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
Reply
#4
Right, one is a regular slice and the other a slice assignment.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Fix pandas copy/slice warning. deanhystad 3 817 Sep-07-2023, 03:18 PM
Last Post: deanhystad
  Value error when converting hex value to bytearray shubhamjainj 7 10,485 Mar-20-2023, 05:30 PM
Last Post: Skaperen
  appending to a bytearray Skaperen 21 14,209 Mar-19-2023, 11:05 PM
Last Post: Skaperen
  Split Bytearray into separate Files by Hex delimter lastyle 5 2,629 Mar-09-2023, 07:49 AM
Last Post: bowlofred
  Save multiple Parts of Bytearray to File ? lastyle 1 939 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  bytearray object - why converting to ascii? Chepilo 2 1,613 Nov-21-2022, 07:25 PM
Last Post: Chepilo
  Slice creates new objects? fmr300 4 1,296 Jul-20-2022, 12:34 PM
Last Post: fmr300
  InvalidIndexError: (slice(None, None, None), slice(None, -1, None)) SuperNinja3I3 1 4,392 Jul-15-2022, 05:59 AM
Last Post: Larz60+
  Slice list Moris526 1 1,641 Dec-24-2020, 02:19 AM
Last Post: deanhystad
  increase and decrease a slice value? KEYS 2 2,090 Nov-10-2020, 11:35 PM
Last Post: KEYS

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020