Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mals14/4bd44e8efc90b28a2475a0061ec0d5e3 to your computer and use it in GitHub Desktop.
Save mals14/4bd44e8efc90b28a2475a0061ec0d5e3 to your computer and use it in GitHub Desktop.
Get value at list/array index or "None" if out of range in Python

I find list slices good for this:

>>> x = [1, 2, 3]
>>> a = x [1:2]
>>> a
[2]
>>> b = x [4:5]
>>> b
[]

So, always access x[i:i+1], if you want x[i]. You'll get a list with the required element if it exists. Otherwise, you get an empty list.

Source: Get value at list/array index or "None" if out of range in Python - Stack Overflow Link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment