Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an element in the middle of a list?

Tags:

I have a list with several elements, say 10.

testList <- split(1:10,1:10) 

How to insert a new element in the middle of the list, say at position 3?

The brute force way of looping through all the elements will work, but just wondering if there is a more elegant way of doing this?

like image 523
Shambho Avatar asked Jul 29 '14 22:07

Shambho


People also ask

How do you add elements to the middle of a set in Python?

The add() method adds a given element to a set. If the element is already present, it doesn't add any element.

How do you add an element to a specific position in an array in Python?

Inserting an element in list at specific index using list. insert() In python list provides a member function insert() i.e. It accepts a position and an element and inserts the element at given position in the list.


1 Answers

I think the append-function is what you are looking for:

append(testList, list(x=42), 3) $`1` [1] 1  $`2` [1] 2  $`3` [1] 3  $x [1] 42  $`4` [1] 4 #snipped.... 

For more complex lists you might find the modifyList function in the utils package to be of use. It allows targeted modifications. What it does not support is insertions of rows in a dataframe.

like image 90
IRTFM Avatar answered Oct 29 '22 02:10

IRTFM