nth

class iteration_utilities.nth(x)

Class that returns the n-th found value.

Parameters:

n : int

The index of the wanted item. If negative the last item is searched.

Note

This is the only parameter for __init__. The following parameters have to be specified when calling the instance.

iterable : iterable

The iterable for which to determine the nth value.

default : any type, optional

If no nth value is found and default is given the default is returned.

pred : callable, optional

If given return the nth item for which pred(item) is True.

Note

pred=None is equivalent to pred=bool.

truthy : bool, optional

If False search for the nth item for which pred(item) is False. Default is True.

Note

Parameter is ignored if pred is not given.

retpred : bool, optional

If given return pred(item) instead of item. Default is False.

Note

Parameter is ignored if pred is not given.

retidx : bool, optional

If given return the index of the n-th element instead of the value. Default is False.

Returns:

nth : any type

The last value or the nth value for which pred is True. If there is no such value then default is returned.

Raises:

TypeError :

If there is no nth element and no default is given.

Examples

Some basic examples including the use of pred:

>>> from iteration_utilities import nth
>>> # First item
>>> nth(0)([0, 1, 2])
0
>>> # Second item
>>> nth(1)([0, 1, 2])
1
>>> # Last item
>>> nth(-1)([0, 1, 2])
2

>>> nth(1)([0, 10, '', tuple(), 20], pred=bool)
20

>>> # second odd number
>>> nth(1)([0, 2, 3, 5, 8, 9, 10], pred=lambda x: x%2)
5

>>> # default value if empty or no true value
>>> nth(0)([], default=100)
100
>>> nth(-1)([0, 10, 0, 0], pred=bool, default=100)
10

Given a pred it is also possible to look for the nth False value and return the result of pred(item):

>>> nth(1)([1,2,0], pred=bool)
2
>>> nth(-1)([1,0,2,0], pred=bool, truthy=False)
0
>>> import operator
>>> nth(-1)([[0,3], [0,1], [0,2]], pred=operator.itemgetter(1))
[0, 2]
>>> nth(-1)([[0,3], [0,1], [0,2]], pred=operator.itemgetter(1), retpred=True)
2

There are already three predefined instances:

__call__(iterable[, default, pred, truthy, retpred, retidx])

Find the n-th element.

n

(int) The index to get (readonly).

New in version 0.6.