Re: How do I test for existence of a list element?

• To: mathgroup at smc.vnet.net
• Subject: [mg112679] Re: How do I test for existence of a list element?
• From: Bob Hanlon <hanlonr at cox.net>
• Date: Sun, 26 Sep 2010 02:44:22 -0400 (EDT)

Depends on what you want to do when you go outside

list = {a, b, c, d};

Use a special value

If[1 <= # <= Length[list], list[[#]], -1] & /@
Range[-1, 6]

{-1, -1, a, b, c, d, -1, -1}

Use a boundary value

list[[Max[1, Min[#, Length[list]]]]] & /@
Range[-1, 6]

{a, a, a, b, c, d, d, d}

Treat the list as cyclic

list[[Mod[# - 1, Length[list]] + 1]] & /@
Range[-1, 6]

{c, d, a, b, c, d, a, b}

Or others

Bob Hanlon

---- Joseph Gwinn <joegwinn at comcast.net> wrote:

=============
I have an application where I am bouncing around in a list, and may
accidentally ask for an element beyond the end of the list, which causes
Mathematica to complain and balk, preventing completion.

Is there any way to test for the existence of a list element without
provoking complaint or balking should the list item fail to exist?

Thanks,

Joe Gwinn

• Prev by Date: Re: How do I test for existence of a list element?
• Next by Date: How do I test for existence of a list element? Clarified
• Previous by thread: Re: How do I test for existence of a list element?
• Next by thread: Re: How do I test for existence of a list element?