lambda in python can iterate dict?
You don't iterate with lambda
. There are following ways to iterate an iterable object in Python:
for
statement (your answer)- Comprehension, including list
[x for x in y]
, dictionary{key: value for key, value in x}
and set{x for x in y}
- Generator expression:
(x for x in y)
- Pass to function that will iterate it (
map
,all
,itertools
module) - Manually call
next
function untilStopIteration
happens.
Note: 3 will not iterate it unless you iterate over that generator later. In case of 4 it depends on function.
For iterating specific collections like dict or list there can be more techniques like while col: remove element
or with index slicing tricks.
Now lambda
comes into the picture. You can use lambdas in some of those functions, for example: map(lambda x: x*2, [1, 2, 3])
. But lambda here has nothing to do with iteration process itself, you can pass a regular function map(func, [1, 2, 3])
.
You can iterate dict using lambda like this:
d = {'a': 1, 'b': 2}
values = map(lambda key: d[key], d.keys())
Using a plain lambda
to iterate anything in Python sounds very wrong. Certainly the most Pythonic method to iterate sequences and collections is to use list comprehensions and generator expressions like @Andrey presented.
If the interviewer was leaning on the more theoretical/Computer Sciencey answers, it is worth noting that using lambdas to iterate is quite possible, although I must stress that this is not Pythonic nor useful at any context other than academic exercises:
# the legendary Y combinator makes it possible
# to let nameless functions recurse using an indirection
Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
# our iterator lambda
it = lambda f: lambda Lst: (Lst[0], f(Lst[1:])) if Lst else None
# see it in action:
Y(it)([1,2,3])
=> (1, (2, (3, None)))