Reputation: 11
I currently use
lindex $mylist end
to get the last element from list in tcl. Mostly mylist values are zeros and I need to get last non-zero element. I know I can put all non-zero elements into a different list or remove zeros from current list. But is there a way to do it without modifying mylist?
Upvotes: 0
Views: 445
Reputation: 4813
As I mentioned in a comment to another answer, a simple way is to use lsearch
to create a new (temporary) list with all zeroes removed, and then get the last element from that list:
lindex [lsearch -all -inline -not -integer $mylist 0] end
I assumed the other elements in the list are also integers. If that is not the case, change the -integer option to -real or -exact.
This may not be the fastest method. But you didn't indicate if that is a concern. At least it will use less memory than creating a reverse list and then using lsearch
to find the first non-zero element. Especially since you indicated the list contains mostly zeroes.
Memory use will not be too bad anyway, because the new (temporary) list will just be a list of pointers to the non-zero elements of the original list. So it doesn't matter if the non-zero elements are short integers too, or happen to be long strings.
Upvotes: 2
Reputation: 137567
The obvious way is to scan backwards through the list:
proc lastNonZero list {
set idx [llength $list]
while {[incr idx -1] >= 0} {
if {[lindex $list $idx] != 0} {
break
}
}
return $idx
}
Upvotes: 2