lrange(3tcl)

πŸ“¦
version 9.0.4 Β· 2 versions
, in debian trixie, ubuntu questing, ubuntu resolute, ubuntu stonking

πŸ’– lrange β€” bestie edition πŸ’–

okay so you know how Tcl lists are literally the moment, and sometimes you just want a slice of one? not the whole thing, just a lil adjacent chunk? yeah. that's this. it's lrange, it's part of the Tcl built-in commands crew, and it's about to hand you one or more adjacent elements from a list. slay. ✨


🌸 SYNOPSIS 🌸

lrange list first last

✨ DESCRIPTION ✨

so. list has to be a valid Tcl list β€” no cap, that's the vibe check. once it passes, this command returns a brand new list made up of the elements from first through last, inclusive. both ends, both included, we don't do exclusion here. 🫢

now the tea on first and last: those index values get interpreted exactly the same way index values work for the command string index. so you get simple index arithmetic and you get indices relative to the end of the list. math girlies rise. πŸ‘‘

and here's the edge-case lore:

  • if first is less than zero, it's treated as if it were zero
  • if last is greater than or equal to the number of elements in the list, it's treated as if it were end
  • if first is greater than last, you get an empty string back. nothing. void. the audacity 😭
okay this next bit is important so pay attention bestie πŸ’… β€” lrange list first first does not always produce the same result as lindex list first. it often does, but only for simple fields that aren't enclosed in braces. what it does produce, exactly, is the same results as list [lindex list first]. remember that. it's on the exam. πŸ“

πŸŽ€ EXAMPLES πŸŽ€

selecting the first two elements β€” classic, iconic:

% lrange {a b c d e} 0 1
a b

selecting the last three elements β€” end relative indexing ate that fr fr:

% lrange {a b c d e} end-2 end
c d e

selecting everything except the first and last element β€” the "no thank you to the edges" special:

% lrange {a b c d e} 1 end-1
b c d

and now the one that catches everybody slipping: selecting a single element with lrange is not the same as doing so with lindex. look at this glow-up difference:

% set var {some {elements to} select}
some {elements to} select
% lindex $var 1
elements to
% lrange $var 1 1
{elements to}

see how lrange kept the braces?? yeah. it returns a list, and a list with one element needs its braces. that's just how it is. πŸ¦‹


πŸ‘‘ SEE ALSO πŸ‘‘

go read these next, they're all in the same friend group:


πŸ’œ KEYWORDS πŸ’œ

element, list, range, sublist


mwah πŸ’‹ that's the whole page. this one came from the Tcl manual set, version 7.4, dated back in the day, and it lives in section 3tcl under the name lrange. go forth and slice those lists, bestie. you got this πŸŒˆπŸ’–βœ¨

πŸ“¦ where this page comes from