9 ms·
Python List Comprehensions Explained Visually
- coherentpony 11y agoIs it just me or were there zero visualisations in this post?
- bgilroy26 11y agoIt might not be what you were expecting, but there's an animation if you ctrl-f "Here’s the transformation animated:"
- coherentpony 11y ago:) I did see that one and indeed it wasn't what I was expecting.
- deleted 11y ago[deleted]
- skadamat 11y agoNot sure how this is visual, neat post either way!
- tsurantino 11y agoFor those confused - the visual part is done in a GIF (i.e. http://treyhunner.com/images/list-comprehension-condition.gif http://treyhunner.com/images/list-comprehension-condition.gi...). I think animating the transformation from a normal loop to a list comprehension is a great way to show how the syntax translates between the two forms. Very awesome and comprehensive post.
- hatmatrix 11y agoMaybe I'm an FP snob but it would have been nice to mention the analogy to set builder notation (though lists aren't sets - maybe multisets or bags) to indicate the existence of higher abstraction; not just syntactic sugar on the for-loop. However, from a practical point of view I think it is great introduction for procedural programmers to begin using list comprehensions.
- deleted 11y ago[deleted]
- msellout 11y agocollections.Counter was designed with multiset in mind.
- dragonwriter 11y ago> though lists aren't sets - maybe multisets or bags arrays/lists (like maps/hashes, though with a more narrow restriction on the indices) are (or at least are isomorphic to) sets of pairs of (index, element). They carry information about order which does not exist in multisets/bags.
- ebola1717 11y agoThat translation is kind of why i don't like python list comprehensions though. It's often clearer as a for-loop or map/filter, cause the different predicates are broken out into separate lines, rather than lumped together in one long line.
- sanderjd 11y agoI'm a big fan of just using map/filter, but I think it makes sense to wonder whether such a common and important operation is worth its own syntax. I do think the way nesting works is a bit surprising. It didn't really occur to me until reading an earlier comment that in essence the most nested loop is a `map` and all the others are `flatMap`s. (I think?)
- d0mine 11y agoThe way to understand how the nesting works in the list comprehension: L = [] for x in X: for y in Y: L.append(x*y) [loops] translate to L = [x*y for x in X for y in Y] If you understand the order of the loops in the first code fragment; you should understand the order in the second one -- it is the same order.
- dragonwriter 11y agoThe problem is that the relation of the body to the loop specifications is reversed, so the inner loop is most proximate to the body in the first, but most distant from the body in the second. The specification of the inner loop should always be most proximate to the body, not last independent of the location of the body.
- sanderjd 11y agoAs a person who thinks about this stuff in more functional terms, as in mapping over collections, rather than imperatively iterating and appending, it helps me to realize how it translates to map and flatMap rather than how it translates to for loops (which I already realized).
- 11y ago
- keepitsurreal 11y agoI've been reviewing Python this week and this was a great brush up. Thanks!
- cballard 11y ago> Sometimes a programming design pattern becomes common enough to warrant its own special syntax. Python’s list comprehensions are a prime example of such a syntactic sugar. I disagree with this thesis, although the post is otherwise a very nice guide to list comprehensions. Special syntax for specific types indicates a failure of the language to be generic enough. List comprehensions anoint lists as a special thing. You don't get to play with list comprehensions, unless you're using the type that the language has decided to let you play with. If you decide to use a different type for some reason, you... can't. map and filter can be part of a typeclass/interface/protocol (in Python these would just be informal), so you can use them on arbitrary types. If you want to switch your list type, it should just work. I write a lot of Swift, and I'm constantly frustrated that optional chaining (?.) and exceptions are special things. I can't implement ?. for my type (say, a Result). Only the language creators can use it. Somewhat confusingly, ?? is a thing I can implement. In Python's case, I think that list comprehensions are necessary because the language's support for first-class closures is poor.
- leni536 11y ago> You don't get to play with list comprehensions, unless you're using the type that the language has decided to let you play with. If you decide to use a different type for some reason, you... can't. You can use generator expressions and pass it to your custom type's constructor. https://www.python.org/dev/peps/pep-0289/ https://www.python.org/dev/peps/pep-0289/
- sanderjd 11y agoYeah, it would be neater if they were just "iterable comprehensions" and worked with anything that is iterable.
- th 11y agoThat's kind of what generator expressions are actually :) https://www.python.org/dev/peps/pep-0289/ https://www.python.org/dev/peps/pep-0289/ You can pass them into anything that expects an iterable. That's pretty much the same since iterable types will frequently consume an iterable in their constructor. For example, here's a "tuple comprehension" (really just a generator expression passed to a tuple): >>> tuple(x for x in [1, 2, 3]) Same thing passed to list and set constructors (which you'd never do because we have the special comprehension syntax for those: >>> list(x for x in [1, 2, 3]) >>> set(x for x in [1, 2, 3]) I explained these in a very slightly different way in the linked webinar I linked in the post: https://youtu.be/u-mhKtC1Xh4?t=35m05s https://youtu.be/u-mhKtC1Xh4?t=35m05s
- danso 11y agoComing from Ruby to Python...I could not believe how damn hard it was to comprehend the beautifully explained and simple code (just 21 lines!) in Peter Norvig's writeup of how to create a spelling corrector [1], purely because of the list comprehensions (and a few other visual differences, such as partial list notation) For example: inserts = [a + c + b for a, b in splits for c in alphabet] It's no different (conceptually, at least) than doing: inserts = [] for a, b in splits: for c in alphabet: inserts.append(a + c + b) Or in Ruby (OK, maybe this isn't perfect Ruby): inserts = splits.reduce([]) do |x, (a, b)| alphabet.each{|c| x << a + c + b } x end But the list comprehension was so difficult for me to read that it might as well have been a brand new concept. But I found I got quickly over it after rewriting all of his comprehensions as for-loops, and then trying to convert them back into comprehensions. It was a good reminder that sometimes the barrier is just plain muscle/memory reflex (and probably much more so for beginning programmers...) [1] http://norvig.com/spell-correct.html http://norvig.com/spell-correct.html
- mjevans 11y agoI most frequently use List Comprehensions in a nested manor, whenever I do that I /ignore/ the normal python syntax and do this for readability. inserts = [ a + c + b for a, b in splits for c in alphabet ] It has the effect of showing the nested loops stacked like they would be in code, but without intending.
- orf 11y ago> I /ignore/ the normal python syntax Is it not normal to do that? I always lay out the nested ones, and even single comprehensions if the conditional is complex.
- gary_bernhardt 11y agoYes, that's very common formatting (except for the whitespace immediately inside the square brackets, which violates PEP 8, but that's incidental to the question of line breaks).
- tsumnia 11y agoMaybe its me, but "Explained Visually" sounds more like it would have some 'visual' aspect to it besides a GIF of code (don't get me wrong, I think most code should be made an image to limit copy/pasting). A website like VisuAlgo (http://visualgo.net/ http://visualgo.net/) is a great example of exampling something visually should mean
- ttkeil 11y agoSetosa (http://setosa.io/ http://setosa.io/) hosts some impressive interactive visualizations as well.
- th 11y agoI agree. I was using "List Comprehensions: Now In Color" as a working title but I thought that was too nonsensical. It was actually the colorized code and not the gifs in particular that made me think "visual". Sorry for the misleading title!
- chestervonwinch 11y agoCool. As a math guy, I enjoy the similarity between comprehensions and set-builder notation: https://en.wikipedia.org/wiki/Set-builder_notation https://en.wikipedia.org/wiki/Set-builder_notation
- Gnewt 11y agoIn the opposite direction, having knowledge of Python's list comprehensions (and to some degree, an understanding of lazy evaluation) helped me a ton when set-builder notation was introduced in my first discrete math class.
- th 11y agoAgreed! Haskell's list comprehensions look even more like set-builder notation: https://wiki.haskell.org/List_comprehension https://wiki.haskell.org/List_comprehension
- y04nn 11y agoWhen I started to learn Python, I was quite lost with this feature, but now I love using it.
- plusquamperfekt 11y agoIs it really that hard to grasp?
- c3534l 11y agoFrankly, comprehensions are one of Python's worst features. Some properly implemented functional syntax would be both more readable and concise. Plus double-nested (I'm not sure what you'd call it) comrpehensions seem to be backwards. Rather than [ingredient for ingredient in recipe for recipe in cookbook] it's [ingredient for recipe in cookbook for ingredient in recipe] which makes it sound as if there's only going len(recipe) number of ingredients in your list. Plus it's so verbose and horizontal, half the time if you want descriptive names you're gonna write something so verbose it doesn't even make it that much more readable.
- oinksoft 11y agoHaskell, Erlang, and Clojure all have sane lambdas (assuming that's what you mean by "properly implemented functional syntax"), and list comprehensions are useful and idiomatic in those languages. Agreed about sequence names feeling out-of-order in nested comprehensions in Python.
- darkerside 11y agoFrom the Zen of Python: > There should be one-- and preferably only one --obvious way to do it. If you have something written as a simple for loop, there's a real danger that you're moving in the wrong direction by translating it into a list comprehension.
- iamsohungry 11y ago> Plus double-nested (I'm not sure what you'd call it) comrpehensions seem to be backwards. Why are you even doing this? This isn't an acceptable way to write code. > Plus it's so verbose and horizontal, half the time if you want descriptive names you're gonna write something so verbose it doesn't even make it that much more readable. If your list comprehension is more than 80 characters wide, it's not because list comprehensions are bad, it's because you did something too complicated. Pull it into a function and name it so people know what the hell you're doing.
- has2k1 11y agoWhen reading code I find comprehensions easier to comprehend than combinations of map, filter and reduce. That is considering that I played around with some Common-Lisp before getting into Python. The parts in the comprehension [*wanted* *iteration(s?)* *condition?*] compares well to *iterations(s?)* *condition?* *append wanted* for normal looping behaviour without changing order of the iterations. One of my favourite comprehensions is of the sort [item for item in items in for i in (0, 1)] of course this can be the same as list(items) * 2 but the comprehension is more versatile [item for item in items in for i in (0, 1) if items[0] != 'a'] For most once the mental fog clears comprehensions become natural very quickly as they are not that far removed from normal loops.
- sdrothrock 11y agoOne basic misstep here for me is a comparison of why list comprehensions are better than loops -- speed, ease of reading, etc. There are a lot of comparisons, but no discussion of WHY list comprehensions. I work on a project that's written mostly in Python; on occasion, other coworkers have to edit/work with my code and they're not used to Python at all, so I find myself writing for loops instead of list comprehensions for clarity.
- TheCowboy 11y agoI find the utility of list comprehensions is maximized when I'm in a Python shell and dealing with indentation when writing a loop can become obnoxious to edit. I tend to have a Python shell tab open in my terminal throughout the day, and it's nice to bang out a quick loop in a one-liner. When writing actual code, I tend to stick with regular for loops.
- iamsohungry 11y agoAre Python List Comprehensions really hard for people? I feel like my memory of learning them was I saw one in production code I was modifying, intuited what it did, pulled open a REPL and played with it for a bit, and then moved on.
- brbsix 11y agoI agree. It really surprised me to see this getting so much traffic. I sometimes get hung up with nested comprehensions when I haven't been using them in a while, but other than that, they are quite mundane.
- jredwards 11y agonested comprehensions are kind of a nightmare to read, but basic list comprehensions seem incredibly straightforward to me. So much so that the explanation is more complex.
- deleted 11y ago[deleted]