Easily limit list length without getting error if list is empty?
UpTo
should do it:
Take[list, UpTo[10]]
and
Part[list, ;; UpTo[10]]
You can also use PadRight
with Nothing
(or ##&[]
) as the third argument:
takeUpTo = PadRight[##, Nothing] &;
(* or takeUpTo = PadRight[##, ##&[]] &; *)
Examples:
takeUpTo[Range[5], 3]
{1, 2, 3}
takeUpTo[Range[5], 100]
{1, 2, 3, 4, 5}
takeUpto[{}, 5]
{}