How in Python is the map function used to iterate over a list (iterable) and do the logic on another list(iterable). For example, we have a list of indices as indices
and a list of strings as str_list
. Then, we want to make the the element at index i
taken from indices
of str_list
to be empty. Yes, the indices are guaranteed to be in the range of str_list
length. There are simple ways to do, however, I want to figure out how the map function does work on two separate list scenarios. This I came up with has error:
str_list = map(lambda index : str_list[index] = "", indices)
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
A Lambda function can only contain a single expression. Assignment with the =
operator is a statement, so it doesn't work in your example.
You can do the assignment with list.__setitem__
, however:
>>> strings = ['zero', 'one', 'two', 'three']
>>> indices = [1, 3]
>>> list(map(lambda x: strings.__setitem__(x, ''), indices))
[None, None]
>>> list(strings)
['zero', '', 'two', '']
This is an abuse of map
, so I would advise against doing it for real.