Reputation: 415
I've got a list that looks like:
a_list = ['A','B','C','D']
And I want to achieve something like (able to expand the list):
new_index = 6
new_value = 'AA'
a_list = insert_value(new_index, new_value)
print(a_list)
#['A','B','C','D','','','AA']
And also something like (able to over-write the new_value):
new_index = 2
new_value = 'AA'
a_list = insert_value(new_index, new_value)
print(a_list)
#['A','B','AA','D']
Upvotes: 1
Views: 901
Reputation: 1907
a_list = ['A','B','C','D']
index = [6,2]
for i in index:
if i >= len(a_list):
a_list.extend([''] * (i - len(a_list) + 1))
print(a_list)
a_list[i] = 'BBB'
else:
a_list[i] = 'AAA'
a_list
['A', 'B', 'AAA', 'D', '', '', 'BBB']
Upvotes: 0
Reputation: 13401
I think you need:
def expand_insert(lst, idx, ele):
if len(lst) < idx:
void = idx - len(lst)
for i in range(void):
lst.append("")
lst.append(ele)
else:
lst[idx] = ele
return lst
print(expand_insert(a_list, 6, "AA"))
Upvotes: 2