Let me tell you my rule of thumb for how long a list comprehension should be.
List comprehensions can become ugly, quickly. And if they do, they lose their appeal. A list comprehension that is too long is tough to understand.
Want an example? Just look at the list comprehension below, taken from my high-resolution list comprehension cheatsheet:
# Don't do this 🤮 [func(elem) for sub1 in iterable if cond1(sub1) if cond2(sub1) for sub2 in sub1 if cond3(sub2) for elem in sub2] # Equivalent nested structure: l =  for sub1 in iterable: if cond1(sub1): if cond2(sub1): for sub2 in sub1: if cond3(sub2): for elem in sub2: l.append(func(elem))
I have a couple of rules of thumb I follow when writing list comps. I use those to decide if my list comp is decent or too complicated. Now, obviously, readability is in the eye of the beholder. Therefore, depending on the context, my rules of thumb may not make much sense.
Usually, this is what I go for:
if, I only use a single loop and an
With these rules of thumb in mind, here are some list comprehensions that I think are OK:
nested = [[[1, 2], [3, 4]], []] # 3 loops: # vvv vvv vvv [elem for sub in nested for ssub in sub for elem in ssub] # [1, 2, 3, 4, 5]
name_groups = [["alIce", "ADam", "AbE"], ["Dean", "DiANa"]] # 2 loops, main expression is a long method call: # vvvvvvvvvvvvv vvv vvv [name.capitalize() for group in name_groups for name in group] # ['Alice', 'Adam', 'Abe', 'Dean', 'Diana']
letters = "ABcDEfghIjKLmN" # 1 loop and 1 condition: # vvv vv [letter for letter in letters if letter.isupper()] # ['A', 'B', 'D', 'E', 'I', 'K', 'L', 'N']
And remember, these are just rules of thumb. Use your best judgement and consider the context when writing a list comprehension!
I hope this was useful! Feel free to leave your thoughts below!
If you enjoyed this blog article, you will love the mathspp insider 🐍🚀 newsletter! Join +16.000 others who are taking their Python 🐍 skills to the next level! 🚀