You essentially want to map example.get
on the sequence, and get the first true-ish value. For that, you can use filter
with the default filter function that does exactly that, and get the first of that using next
:
>>> example = {
'answer': 42,
'bring': 'towel'
} >>>
lst = ['dolphin', 'guide', 'answer', 'panic', 'bring'] >>>
next(filter(None, map(example.get, lst)))
42
you can use next()
builtin and generator expression:
next(example[key]
for key in ['dolphin', 'guide', 'answer', 'panic', 'bring']
if key in example)
if you want to use predefined function, it might be better to use filter, which accepts function as the first argument (lambda in example):
next(itertools.ifilter(lambda txt: 'a' in txt, ['foo', 'bar']))
I don't think there's a built in function to do what you want. There is an arguably more Pythonic way of doing what you're doing:
example = {
'answer': 42,
'bring': 'towel'
}
keys = ['dolphin', 'guide', 'answer', 'panic', 'bring']
print filter(lambda x: x, map(example.get, keys))[0]
Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.,Make an iterator that returns elements from the iterable as long as the predicate is true. Roughly equivalent to:,Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument).,Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:
def accumulate(iterable, func = operator.add, *, initial = None): 'Return running totals' # accumulate([1, 2, 3, 4, 5]) -- > 1 3 6 10 15 # accumulate([1, 2, 3, 4, 5], initial = 100) -- > 100 101 103 106 110 115 # accumulate([1, 2, 3, 4, 5], operator.mul) -- > 1 2 6 24 120 it = iter(iterable) total = initial if initial is None: try: total = next(it) except StopIteration: return yield total for element in it: total = func(total, element) yield total
>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8] >>> list(accumulate(data, operator.mul)) # running product[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0] >>> list(accumulate(data, max)) # running maximum[3, 4, 6, 6, 6, 9, 9, 9, 9, 9] # Amortize a 5 % loan of 1000 with 4 annual payments of 90 >>> cashflows = [1000, -90, -90, -90, -90] >>> list(accumulate(cashflows, lambda bal, pmt: bal * 1.05 + pmt))[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001] # Chaotic recurrence relation https: //en.wikipedia.org/wiki/Logistic_map >>> logistic_map = lambda x, _: r * x * (1 - x) >>> r = 3.8 >>> x0 = 0.4 >>> inputs = repeat(x0, 36) # only the initial value is used >>> [format(x, '.2f') for x in accumulate(inputs, logistic_map)] ['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63', '0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57', '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32', '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60' ]
def chain( * iterables):
# chain('ABC', 'DEF') -- > A B C D E F
for it in iterables:
for element in it:
yield element
def from_iterable(iterables):
# chain.from_iterable(['ABC', 'DEF']) -- > A B C D E F
for it in iterables:
for element in it:
yield element
def combinations(iterable, r):
# combinations('ABCD', 2) -- > AB AC AD BC BD CD
# combinations(range(4), 3) -- > 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
yield tuple(pool[i]
for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i + 1, r):
indices[j] = indices[j - 1] + 1
yield tuple(pool[i]
for i in indices)
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
for indices in permutations(range(n), r):
if sorted(indices) == list(indices):
yield tuple(pool[i]
for i in indices)
Last Updated : 07 Jul, 2022
Syntax :
map(fun, iter)
Returns :
Returns a list of the results after applying the given
function
to each item of a given iterable(list, tuple etc.)
Output :
[2, 4, 6, 8]
Last modified: Jul 14, 2022, by MDN contributors
TypeError: object is not iterable(cannot read property Symbol(Symbol.iterator))(V8 - based)
TypeError: x is not iterable(Firefox)
TypeError: undefined is not a
function(near '...[x]...')(Safari)
const myobj = {
arrayOrObjProp1: {},
arrayOrObjProp2: [42]
};
const {
arrayOrObjProp1: [value1],
arrayOrObjProp2: [value2]
} = myobj; // TypeError: object is not iterable
console.log(value1, value2);
const obj = {
France: 'Paris',
England: 'London'
};
for (const p of obj) { // TypeError: obj is not iterable
// …
}
const obj = {
France: 'Paris',
England: 'London'
};
// Iterate over the property names:
for (const country of Object.keys(obj)) {
const capital = obj[country];
console.log(country, capital);
}
for (const [country, capital] of Object.entries(obj)) {
console.log(country, capital);
}
const map = new Map;
map.set('France', 'Paris');
map.set('England', 'London');
// Iterate over the property names:
for (const country of map.keys()) {
const capital = map.get(country);
console.log(country, capital);
}
for (const capital of map.values()) {
console.log(capital);
}
for (const [country, capital] of map.entries()) {
console.log(country, capital);
}
function* generate(a, b) {
yield a;
yield b;
}
for (const x of generate) { // TypeError: generate is not iterable
console.log(x);
}
The iter() function (which in turn calls the __iter__() method) returns an iterator from them.,We use the next() function to manually iterate through all the items of an iterator. When we reach the end and there is no more data to be returned, it will raise the StopIteration Exception. Following is an example.,The __iter__() method returns the iterator object itself. If required, some initialization can be performed.,Building an iterator from scratch is easy in Python. We just have to implement the __iter__() and the __next__() methods.
We use the next()
function to manually iterate through all the items of an iterator. When we reach the end and there is no more data to be returned, it will raise the StopIteration
Exception. Following is an example.
# define a list my_list = [4, 7, 0, 3] # get an iterator using iter() my_iter = iter(my_list) # iterate through it using next() # Output: 4 print(next(my_iter)) # Output: 7 print(next(my_iter)) # next(obj) is same as obj.__next__() # Output: 0 print(my_iter.__next__()) # Output: 3 print(my_iter.__next__()) # This will raise error, no items left next(my_iter)
Output
4
7
0
3
Traceback (most recent call last):
File "<string>", line 24, in <module>
next(my_iter)
StopIteration
A more elegant way of automatically iterating is by using the for loop. Using this, we can iterate over any object that can return an iterator, for example list, string, file etc.
>>>
for element in my_list:
...print(element)
...
4
7
0
3
Is actually implemented as.
# create an iterator object from that iterable iter_obj = iter(iterable) # infinite loop while True: try: # get the next item element = next(iter_obj) # do something with element except StopIteration: # if StopIteration is raised, break from loop break
If you do not have any idea about object-oriented programming, visit Python Object-Oriented Programming.
class PowTwo: "" "Class to implement an iterator of powers of two "" " def __init__(self, max = 0): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): if self.n <= self.max: result = 2 ** self.n self.n += 1 return result else: raise StopIteration # create an object numbers = PowTwo(3) # create an iterable from the object i = iter(numbers) # Using next to get to the next iterator element print(next(i)) print(next(i)) print(next(i)) print(next(i)) print(next(i))