user3914448
user3914448

Reputation: 499

How to insert element between other elements in KDB/Q list

Say I have a list (1 3 4) and after 1 I want to insert another element 2 resulting in (1 2 3 4).

How can this be done efficiently in a generic way?

Upvotes: 2

Views: 2493

Answers (2)

terrylynch
terrylynch

Reputation: 13572

An alternative approach which allows for multiple inserts at once.

If the indices are to index the original list:

q){raze cut[(0,z);x],'(y,enlist ())}[til 10;999 998 994;2 4 8]
0 1 999 2 3 998 4 5 6 7 994 8 9

If the indices are to index consecutive iterations of the list:

q){raze cut[(0,z);x],'(y,enlist ())}/[til 10;999 998 994;2 4 8]
0 1 999 2 998 3 4 5 994 6 7 8 9

Upvotes: 1

zak.oud
zak.oud

Reputation: 152

I think you need to be more specific about what you want, but for now here's an example of how you could achieve it

q)list:1 3 4
q)list
1 3 4
q)list: asc list,:2
q)list
`s#1 2 3 4

Or another way is let's say you know the index at which you want to add the element to the list, in this case at index 1, then you could create a function as such:

q)add:{[lst;ele;ind] (ind#lst),ele,(ind _ lst)}
q)list:1 3 4
q)add[list;2;1]
1 2 3 4

Upvotes: 0

Related Questions