Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python map iterate over a list and function on another list

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 "=="?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading