Insert Item to end of list at index

Hello all,

I am trying to insert items to the end of a list at an index. I cannot seam to get it to work though. Sorry if my poor explanation, I am having a hard time trying to explain it.

I have a list with sub list.
List of Index’s
and a list of items to be added. I want one item to be added to to the end of each sub list at of the corresponding index. Right now the whole list of items creates a new sub list.

Thank for the help,

Could you sketch what you would like your result to be?

Thanks for the quick reply I will add something tomorrow on my way out the door.

@Steven is this what you’re looking for?

2 Likes

I think he wants the second list inserted only at certain indexes (Insert node’s index). Don’t have python open right now and I know there is a better way but something like this would work assuming index is always in numerical order:

list1 = IN[0]
list2 = IN[1]
indexes = IN[2]

count = 0

for i in range(len(list1)):
	if i == indexes[count]:
		list1[i].append(list2[count])
		count += 1

or try this:

list1 = IN[0]
list2 = IN[1]
indexes = IN[2]

for i in range(len(indexes)):
    list1[indexes[i]].append(list2[i])
3 Likes

@kennyb6 solution should work.

You could also try this:

list1 = IN[0]
list2 = IN[1]
indexes = IN[2]

for i,j in zip (list2,indexes):list1[j].append(i)
    
OUT=list1 

image

5 Likes

Can anybody make it work with nodes only? I can’t make it work with OOTB List.ReplaceItemAtIndex node.

1 Like

An OOTB solution …
AddLastAtIndex.dyn (6.7 KB)

5 Likes

Glad you were able to have fun with this one. I am not sure what to mark as a solution since you all have given really good ones.

Thanks every one this is very helpful and a great learning experience.

Steven

2 Likes

I did Vikram’s OOTB solution since it is the most straight forward and done without code. I really like the coded work flows but for others looking for the solution I figured it best.

1 Like

ok.This is weird!..I just changed the data and it does’t work?

AddLastAtIndex 2.dyn (10.5 KB)

@salvatoredragotta Works with alterations. :slight_smile:


AddLastAtIndex1.dyn (6.7 KB)

1 Like

If the builtin Reorder node worked and if your data does not have any null values, it should be as simple as:

image

2 Likes

what about cases with consecutive indices? :slight_smile:

Let’s say we’re interested in extending only the sublists at {1, 2, 4} ?

Another (less convoluted) OOTB approach…
AddLastAtIndex2.dyn (10.9 KB)


Design Script version of the above …

a = List.GetItemAtIndex(lst,idx);
b = List.AddItemToEnd(itm<1>,a<1>);
c = SetDifference(GetKeys(lst),idx);
d = List.GetItemAtIndex(lst,c);
e = List.Flatten({b,d},1);
f = List.Flatten({idx,c},1);
g = List.SortByKey(e,f)["sorted list"];
3 Likes

Solution via Design Script using “insert”