When to use map over list comprehension | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

When to use map over list comprehension

When should i be using map than list comprehension? Is it when i want to return a tuple or a string or another iterable? It seems as list comprehension and map both do the same thing, so what is the real the difference?

22nd Jul 2023, 10:12 PM
Junior
Junior - avatar
5 Answers
+ 4
Junior on this example you can see that the iteration through the list, which is formed by applying the function to the data, takes twice as much time as the generation of the same chain by the map function. This is because the generator does not need to first create the full list and iterate over it, it generates the elements in place without using extra memory for store all the results. https://code.sololearn.com/cadDe4S17DMI/?ref=app
23rd Jul 2023, 2:45 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 6
Map returns an iterator that applies a function to each element of the iterable that produces the results. That is, it is a generator to which the next() function can be applied. This can save you memory resources when calculating a large amount of data, as opposed to the list comprehension, which returns the list itself calculated in the expression already at the stage of its interpretation or assignment.
23rd Jul 2023, 2:57 AM
Vitaly Sokol
Vitaly Sokol - avatar
+ 1
Vitaly Sokol What exactly do you mean by large amount of data?
23rd Jul 2023, 3:34 AM
Junior
Junior - avatar
+ 1
Vitaly Sokol I see thank you
23rd Jul 2023, 3:36 PM
Junior
Junior - avatar
+ 1
Vitaly Sokol So here would be better for list comprehension since im not using a large amount of data? numbers = input().split() numbers_comprehension = [int(number) for number in numbers]
23rd Jul 2023, 8:08 PM
Junior
Junior - avatar