How to get the nth element of a python list or a default if not available

PythonList

Python Problem Overview


I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available?

For example, given a list myList I would like to get myList[0], or 5 ifmyList is an empty list.

Thanks.

Python Solutions


Solution 1 - Python

l[index] if index < len(l) else default

To support negative indices we can use:

l[index] if -len(l) <= index < len(l) else default

Solution 2 - Python

try:
   a = b[n]
except IndexError:
   a = default

Edit: I removed the check for TypeError - probably better to let the caller handle this.

Solution 3 - Python

(a[n:]+[default])[0]

This is probably better as a gets larger

(a[n:n+1]+[default])[0]

This works because if a[n:] is an empty list if n => len(a)

Here is an example of how this works with range(5)

>>> range(5)[3:4]
[3]
>>> range(5)[4:5]
[4]
>>> range(5)[5:6]
[]
>>> range(5)[6:7]
[]

And the full expression

>>> (range(5)[3:4]+[999])[0]
3
>>> (range(5)[4:5]+[999])[0]
4
>>> (range(5)[5:6]+[999])[0]
999
>>> (range(5)[6:7]+[999])[0]
999

Solution 4 - Python

Just discovered that :

next(iter(myList), 5)

iter(l) returns an iterator on myList, next() consumes the first element of the iterator, and raises a StopIteration error except if called with a default value, which is the case here, the second argument, 5

This only works when you want the 1st element, which is the case in your example, but not in the text of you question, so...

Additionally, it does not need to create temporary lists in memory and it works for any kind of iterable, even if it does not have a name (see Xiong Chiamiov's comment on gruszczy's answer)

Solution 5 - Python

(L[n:n+1] or [somedefault])[0]

Solution 6 - Python

> ... looking for an equivalent in python of dict.get(key, default) for lists

There is an itertools recipes that does this for general iterables. For convenience, you can > pip install more_itertools and import this third-party library that implements such recipes for you:

Code

import more_itertools as mit


mit.nth([1, 2, 3], 0)
# 1    

mit.nth([], 0, 5)
# 5    

Detail

Here is the implementation of the nth recipe:

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(itertools.islice(iterable, n, None), default)

Like dict.get(), this tool returns a default for missing indices. It applies to general iterables:

mit.nth((0, 1, 2), 1)                                      # tuple
# 1

mit.nth(range(3), 1)                                       # range generator (py3)
# 1

mit.nth(iter([0, 1, 2]), 1)                                # list iterator 
# 1  

Solution 7 - Python

Combining @Joachim's with the above, you could use

next(iter(my_list[index:index+1]), default)

Examples:

next(iter(range(10)[8:9]), 11)
8
>>> next(iter(range(10)[12:13]), 11)
11

Or, maybe more clear, but without the len

my_list[index] if my_list[index:index + 1] else default

Solution 8 - Python

Using Python 3.4's contextlib.suppress(exceptions) to build a getitem() method similar to getattr().

import contextlib

def getitem(iterable, index, default=None):
    """Return iterable[index] or default if IndexError is raised."""
    with contextlib.suppress(IndexError):
        return iterable[index]
    return default

Solution 9 - Python

A cheap solution is to really make a dict with enumerate and use .get() as usual, like

 dict(enumerate(l)).get(7, my_default)

Solution 10 - Python

Althought this is not a one-liner solution, you can define a function with a default value like so:

def get_val(myList, idx, default=5):
    try:
        return myList[idx]
    except IndexError:
        return default

Solution 11 - Python

After reading through the answers, I'm going to use:

(L[n:] or [somedefault])[0]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser265454View Question on Stackoverflow
Solution 1 - PythongruszczyView Answer on Stackoverflow
Solution 2 - PythonTim PietzckerView Answer on Stackoverflow
Solution 3 - PythonJohn La RooyView Answer on Stackoverflow
Solution 4 - PythonJoachim JablonView Answer on Stackoverflow
Solution 5 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 6 - PythonpylangView Answer on Stackoverflow
Solution 7 - Pythonserv-incView Answer on Stackoverflow
Solution 8 - PythonHarveyView Answer on Stackoverflow
Solution 9 - PythonScorchioView Answer on Stackoverflow
Solution 10 - PythonezzeddinView Answer on Stackoverflow
Solution 11 - PythonMathieu CAROFFView Answer on Stackoverflow