List functions

1. To create a list:

Syntax: list elem1 %elem2 elem3 ... %

creates a list of specified elements.

Example:

% set L1 [ list $a $b $c [ set d 10 ] ]

2. To concat 2 or more lists


Syntax: concat list1 list2 % ... %


Example:
% set L1 [ concat {a b c} $L2 {x y z} ]

3. To return number of elements

Syntax: llength $L1

4. To return an element at specified index in a list

Syntax: lindex list_name index1 %index2 ...%


Example:

%set L1 { 10 20 { C { D E } F G } }
% lindex L1 1
20
% lindex L1 2
C { D E }
% lindex L1 2 1
D E
% lindex L1 2 1 1 
E

Second & subsequent indexes refers to list received due to previous index.


5. To add new elements, or delete a few existing ones


Syntax: lset Listname indx1 indx2 [newelem]

Used to modify list.

If newelem is absent, all elements between indx1 and indx2 are removed.
If newelem is present, first elements between indx1 and indx2 are removed and in its place new element is added
If indx1 < indx2 then no elements are removed
If indx1 and indx2 then new element is prepended


Original list is modified.

6. To append new elements to the list

Syntax: lappend Listname elem1 [ elem2 …]



Original list is modified.

7. To replace a few set of elements with new elements

Syntax: lreplace List indx1 indx2 [ elem1 elem2 ... ]

First all elements between indx1 and indx2 are removed ( both inclusive), then new elements are added starting feom indx1
Changes are made on a copy of list
If indx1 < indx2 then no elements are removed
If indx1 and indx2 then new element is prepended

Example:
% set L1 { 10 20 30 40 50 }
% puts [ lreplace $L1 0 2 100 ]


100 40 50

8. To insert a few new elements


Syntax: linsert List indx1 [ elem1 … ]



New elements are added at position indx1 by making room for new elements.
Original list is not modified.

9. To fetch a set of elements from the list

Syntax: lrange alist indx1 indx2

All elements between indx1 and indx2 are returned
Original list is not modified.

10. To sort a list

Syntax: lsort options List

options: -increasing -ascii -decreasing -integer -real -index num

Example:
If you want to sort based on 2nd element of each sublist
set L1 { { c 2 } { b 1 } { a 3 } { d 4} }
puts [ lsort -index 1 $L1 ]
{ b 1 } { c 2 } { a 3 } { d 4 }

11. To search an element in the list

Syntax: lsearch option List pattern

option: -exact -glob -regexp
Returns index of matched element

12. To split a string based on delimiting characters and return a list of elements:

Syntax: split string [ delimChar ]
Default is space character
Every character is taken separately
puts [ split bpbayax ba]
{} p {} y x

13. To join a list and return a single string.

Syntax: join List [ delimChar ]

A string is returned with elements appended one after another separated by a delimChar.



Comments

Popular posts from this blog

What should you expect in an VLSI interview as a fresher

The struggle to enter VLSI industry is for real