Inserting elements into a list

Now that we have an introduction to the usage of indices within a list, it is time to investigate how to insert items into a list at an arbitrary position as opposed to simply appending data. To accomplish this, Tcl provides the linsert command. The syntax is as follows:

	linsert list index element1 element2 …

How to do it…

In the following example, we will insert an element into a list at a predefined location. Return values from the commands are provided for clarity. Enter the following command:


% set input {John Mary Bill}
John Mary Bill

% set newinput [linsert $input 1 Tom]
John Tom Mary Bill

% puts $input
John Mary Bill

% puts $newinput
John Tom Mary Bill

How it works…

The linsert command returns a new list from the list provided by inserting additional elements just before the element referenced by the index. This was illustrated by creation of the list newinput and the subsequent puts commands to display the contents of both the original and new lists. If the value contained in the index is less than or equal to 0, it will be inserted at the beginning.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.245.1