Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning Values to an Array with for Loop Python

I'm trying to assign the values of a string to different array indexes

but I'm getting an error called "list assignment out of range"

uuidVal = ""
distVal = ""
uuidArray = []
distArray = []

for i in range(len(returnedList)):
     for beacon in returnedList:
            uuidVal= uuidVal+beacon[:+2]
            uuidArray[i]= uuidVal
            distVal= distVal+beacon[-2:]
            distArray[i]= distVal
            uuidVal=""
            disVal=""

I tried using

distArray[i].append(distVal)

instead of

distArray[i]= distVal

but it gave an error called "list index out of range"

Using

distArray.append(distVal)

made it work with no error but the outcome was wrong

because it keep concatenating the new assigned value with old values in the next index

How it should work:

returnedList['52:33:42:40:94:10:19, -60', '22:34:42:24:89:70:89, -90', '87:77:98:54:81:23:71, -81']

with each iteration it assign the first to char to uuidVal (ex: 52, 22, 87) and the last two char to distVal (ex: 60, 90, 81)

at the end uuidArray should have these values [52, 22, 87]

and distArray should have these values [60, 90, 81]

Note: using .append concatenate the values, for example if used with distArray like distArray.append(distVal) the values will be like this [60, 6090, 609081]

like image 473
AMS91 Avatar asked Dec 20 '22 08:12

AMS91


1 Answers

yes you will get error list index out of range for:

distArray[i] = distVal

you are accessing the index that is not created yet

lets see this demo:

>>> a=[]   # my list is empty 
>>> a[2]    # i am trying to access the value at index 2, its actually not present
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

your code should be like this:

uuidArray = []
distArray = []
distVal = ""
for beacon in returnedList:
        uuidArray.append(beacon[:2])
        distval += beacon[-2:]
        distArray.append(distVal)

output will be uudiArray: ['52', '22', '87'] and distArray: ['60', '6090', '609081']

like image 107
Hackaholic Avatar answered Dec 30 '22 02:12

Hackaholic