17
Finally tried Python list comprehensions vs writing out for loops
Had to process 500 user names last night and the list comprehension version was literally half the code and ran faster. Has anyone else found a moment where a simple syntax change just clicked for you?
2 comments
Log in to join the discussion
Log In2 Comments
dixon.ryan1mo ago
500 names is a solid test case but its worth noting that list comprehensions aren't always faster than loops, especially if you're doing something complex inside the comprehension. They do win on readability and less code once you get used to them though. The real click moment for me was realizing you can nest them too, just gotta keep it simple or it gets unreadable fast.
6
averym8229d ago
Exactly what @dixon.ryan said about nesting, that's where it gets fun but also where people go off the rails trying to be clever. Keep the inner part dead simple and it's golden, otherwise a plain old loop is way easier to debug later.
2