I wrote this function to fill a list with object based on the desired index they should have.
Here the func:
def fill(lst, index, add, fillvalue=None):
'''Fills a list with the add value based on desired index'''
'''Let the value in place if present'''
for n in range(index):
try:
if lst[n]:
pass
except Exception:
lst.append(fillvalue)
try:
if lst[index]:
pass
else:
lst[index]=add
except Exception:
if index==len(lst):
#This if check probably not mandatory
lst.append(add)
return lst
edit: here's an usage example that would for example happen in a for loop
>>> my_list = [1, 7, 14]
>>> fill(my_list, 5, 6)
[1, 7, 14, None, None, 6]
>>> fill(my_list, 6, 12)
[1, 7, 14, None, None, 6, 12]
>>> fill(my_list, 3, 25)
[1, 7, 14, 25, None, 6, 12]
>>> fill(my_list, 4, 18)
[1, 7, 14, 25, 18, 6, 12]
Note:
>>> my_list = [1, 7, 14]
>>> fill(my_list, 1, 6)
#returns the list not modified, my_list[1] is already taken
[1, 7, 14]
It works good for my purpose (matrix generating). My matrixes are generated with many "for loops" passes, because the data I convert to is unordered. This is why the "None" elements are important in order to fill them out on a subsequent loop pass.
My questions are:
I'm wondering if I made everything as simple as possible? Or if there were a lib, that would do the same job?
For now the matrixes aren't so long but I guess, if I go further in my development, they will become big (1000+ lines). Should I somehow better use itertools?
I also somehow thought of first using a dict {index: value} and convert it to a list when filled up. Would it be better practice?
Edit: Now that I pasted the code in here I notice the arg name "add" is blued. My Vim-editor didn't told me that... Is it a name already taken by the python core?
except Exception:
like that is a bad idea, see stackoverflow.com/questions/54948548/…. \$\endgroup\$