Is this dictionary comprehension realistically used?

Do coders use this much? It looks borderline unreadable to me. Mind that I’m a beginner. I just thought python was supposed to readable first in case some else is working off your code in the future. I get that this is new syntax to me, and its seems like we went 0-100 mph, but does list comprehension get used much in real world applications as it seems garbled? I guess what I’m asking is if you could do this without list comprehension AND with the tools/lessons we’ve learned to this point?

1 Like

Anything that can be done with a comprehension can be done without one. I may be argued that comprehensions are faster but only benchmarking can prove whether this is true in any particular instance.

>>> nums = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> times_two = [x * 2 for x in nums]
>>> doubled = map(lambda x: x * 2, nums)
>>> times_two
[2, 2, 4, 6, 10, 16, 26, 42, 68, 110]
>>> doubled
<map object at 0x02E31030>
>>> list(doubled)
[2, 2, 4, 6, 10, 16, 26, 42, 68, 110]
>>> even_nums = [x for x in nums if not x % 2]
>>> evens = filter(lambda x: not x % 2, nums)
>>> even_nums
[2, 8, 34]
>>> evens
<filter object at 0x02E31130>
>>> list(evens)
[2, 8, 34]
>>> 

Of course we can also write algorithms to perform these tasks. This is the basis for writing comprehensions… The writing of working naive algorithms is what opens the door to other levels of abstraction and sophistication. First we need to master that, then begin working with other tools and refinements. If we skip this step we’re not better off for having better tools.

Thank you very much for getting back to me :slight_smile: I think I see what you’re saying with your examples, but I haven’t had experience with lambda(s) yet. I can see how you’re using list comprehension to manipulate nums, and I’ll just have to keep practicing. I can see where it will click. Thanks again, Happy New Year!

1 Like

Be sure to write basic algo’s for those two examples to prove to yourself there is a naive solution for each.

Thank you. I’m working on those now. The map() function is very cool !!

1 Like