Joseph Webber
Joseph Webber

Reputation: 2173

How do I copy the contents of a bytearray to a list (Python)?

I have a dictionary which I convert to a bytearray, and since bytearrays are immutable (can't be modified) I try to make a list equal to each index in the bytearray.

a = {1:'a', 2:'b', 3:'c'}
b = bytearray(str(a), 'ASCII')
c = []

for i in b:
    c[i] = b[i]     # Error on this line

print(str(c))

The problem is it keeps printing IndexError: bytearray index out of range.
How and why is the bytearray out of range?

Upvotes: 2

Views: 2858

Answers (3)

dawg
dawg

Reputation: 103874

To fix your code:

a = {1:'a', 2:'b', 3:'c'}
b = bytearray(str(a), 'ASCII')
c = []

for i in b:
    c.append(i) 

or, better still, you can use the byte array directly with the list constructor and forgo the loop:

c=list(b)

or, skip the byte array and use a list comprehension:

c= [ord(ch) for ch in str(a)]

In all these cases, you get the list of ASCII ordinals if that is your goal:

[123, 49, 58, 32, 39, 97, 39, 44, 32, 50, 58, 32, 39, 98, 39, 44, 32, 51, 58, 32, 39, 99, 39, 125]

Upvotes: 1

aldeb
aldeb

Reputation: 6828

If I correctly understood your question, you can simply use c = list(b):

a = {1:'a', 2:'b', 3:'c'}
b = bytearray(str(a), 'ASCII')
c = list(b)

print(c)

Output:

[123, 49, 58, 32, 39, 97, 39, 44, 
 32, 50, 58, 32, 39, 98, 39, 44, 
 32, 51, 58, 32, 39, 99, 39, 125]

In order to understand why you get this error, see this answer.

Upvotes: 5

Joran Beasley
Joran Beasley

Reputation: 113988

i is the value in b not the index

b = [1,5,20]
for i in b:
   print i #prints 1,then 5 , then 20

Upvotes: 4

Related Questions