Assigning Values to an Array with for Loop Python
Solution 1
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']
Solution 2
When you define distArray as:
distArray = []
You are initializing a list with 0 elements, so distArray[2]
will correctly throw an error, since you are attempting to access an element past the total length of the array.
There are two ways to deal with this:
- Use
append
. This takes the list and extends it by the element contained in the function call. This is to be preferred for all but the rarest of occasions, imo. - Explicitly define an empty list. This can be done using something like:
distArray = [0]*num_elements
, wherenum_elements
is the number of elements you want to have. This will create a list of sizenum_elements
all equal to 0.
Solution 3
Others have already explained the mistake, so I'll just leave my 2c on how to work this out. First of all you can use pure Python:
distArray = [None for _ in xrange(max_value+1)]
I'm using None-type objects to allocate the array (whereas many people prefer zeros) because they can't be interpreted as an integer or bool.
If your process is going to be RAM-intensive, you should better use numpy arrays. And there is a highly efficient way to create an empty array in numpy.
import numpy as np
distArray = np.empty(max_value+1, dtype=str)
Notice that you should manually select a data type.
What you are trying to achieve is basically a simplified hash-map/table. If you're not sure about the maximum value, you can consider writing your own 'dynamic' array, that will increase in size, if called outside its borders, instead of raising the error.
class DistArray():
def __init__(self, starting_size):
self.arr = [None for _ in xrange(starting_size)]
def __getitem__(self, i):
return self.arr[i]
def __iter__(self):
return iter(self.arr)
def insert_item(self, item, value):
try:
self.arr[value] = item
except:
self.arr.extend([None for _ in xrange(value - len(self.arr))])
self.arr[value] = item
This thing will adapt to your needs.
distArray = DistArray(starting_size)
distArray.insert_item(string, value)
AMS91
Updated on September 24, 2020Comments
-
AMS91 almost 4 years
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]
-
AMS91 over 9 yearsThanks, now I understand why my approach is wrong. But what should I do instead to make it work?
-
AMS91 over 9 yearsUsing append will no give an error but the problem it will concatenate the new value with the old values. So if index[0]='81' and the next value is 79, index[1] will equal '8179' and so on. The second method it give wrong output, too long form the beginning. The first one starts great exactly like I wanted but the issue it keep concatenating
-
AMS91 over 9 yearsThe input data is a string containing two digits number. The output should be an array with each index containing a string of two digits numbers. The first loop is used to assign select the index, the second loop is to get a string from an array of string in each iteration. I cannot select indexes with a string value
-
Hackaholic over 9 yearscan u update in ur post with sample input and expected output that will be more clear
-
AMS91 over 9 yearsThx it works now, I was commenting distVal = "" that why it was keeping to concatenate.