How do I efficiently get the rest of the Tcl list, starting at the index?

I would like to get all the elements following a specific index of the list. This can be written as:

set foo {0 1 2 3 4 5 6 <...> n}
puts [lrange $foo 1 [llength $foo]]

      

However, it seems like a waste of time to calculate the length of the list. It would be nice if the last argument to lrange was optional and omitted so that it continues to the end of the list, but alas, this is not the case today.

Is there any other way to do this efficiently in Tcl without calculating the length of the list?

+2


source to share


2 answers


You can use "end" instead of "[llength $ foo]"

So...



puts [lrange $ foo 1 end]

+7


source


Jeff answered your question well. That being said, it is worth noting. Getting the length of a list (actually a list under the hood) is O (1), which means it doesn't take real time. The length of the list itself is stored along with the metadata and is not recalculated. The only real cost is the function call overhead. Using "end" is probably even faster, just not as hard as you might think.



But by "actually a list under the hood," I mean the interpreter currently treats it as a list (there is a deeper explanation, but not worth going in here). Since you are using [lrange] in the value, the interpreter has to convert it internally to a list ... so you pretty much guarantee O (1) behavior on [llength].

+4


source







All Articles