Lucas Mengual
Lucas Mengual

Reputation: 415

Insert into list an element at specific index, overwrite the element at same index or expanding list

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

Answers (2)

vb_rises
vb_rises

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

Sociopath
Sociopath

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

Related Questions