Mic
Mic

Reputation: 53

Insert numbers into list given another list of index numbers

I'm looking to insert a list of numbers (firstNumberList) into specific points in another list (secondNumberList) according to a list of index numbers (indexNumberList).

indexNumberList = [1, 2, 5, 8]
firstNumberList = [0, 0, 0, 0]
secondNumberList = [ 3, 1, 3, 2, 4, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]

I've tried the following list comprehension but it returns [none, none, none, none]

result =[secondNumberlist.insert(indexNumberList[elem],firstNumberList[elem]) for elem in range(len(indexNumberList))]

ultimately the output should look like this

[ 3, 0, 0, 1, 3, 0, 2, 4, 0, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]

Upvotes: 1

Views: 74

Answers (2)

DarkDrassher34
DarkDrassher34

Reputation: 59

If you have numpy installed, this is nicer to read and follow along:

import numpy as np 

indexNumberList = [1, 2, 5, 8]
firstNumberList = [0, 0, 0, 0]
secondNumberList = [ 3, 1, 3, 2, 4, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]

new_array = np.ones(len(secondNumberList) + len(firstNumberList)) * np.nan

new_array[indexNumberList] = firstNumberList
new_array[np.where(np.isnan(new_array))] = secondNumberList

list(new_array)

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

indexNumberList = [1, 2, 5, 8]
firstNumberList = [0, 0, 0, 0]
secondNumberList = [3, 1, 3, 2, 4, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]

for i, v in zip(indexNumberList, firstNumberList):
    secondNumberList = secondNumberList[:i] + [v] + secondNumberList[i:]

print(secondNumberList)

Prints:

[3, 0, 0, 1, 3, 0, 2, 4, 0, 1, 1, 4, 4, 4, 9, 9, 12, 12, 18, 19, 18, 9]

EDIT: Version with list.insert (Thanks to @Chris_Rands):

for i, v in zip(indexNumberList, firstNumberList):
    secondNumberList.insert(i, v)

Upvotes: 3

Related Questions