Articles
Screencasts
Exercises
Training
Pastebin
Gift
/
Sign Up
Sign In
Ternaries in comprehensions: I don't recommend this
Editable Code
"""Ternaries in comprehensions: I don't recommend this""" screencasts = [ "Data structures contain pointers", "What is self?", "What is a class?", "Slicing", "How to make a function", "Methods are just functions attached to classes", ] # Can't copy-paste this to a comprehension due to the "else" and 2 appends shortened = [] for name in screencasts: if len(name) > 30: shortened.append(name[:30-3] + "...") else: shortened.append(name) # An "inline if" statement could collapse that into just one append shortened = [] for name in screencasts: shortened.append(name[:30-3] + "..." if len(name) > 30 else name) # And that could copy-paste into a comprehension shortened = [ f"{name[:30 - 3]}..." if len(name) > 30 else name for name in screencasts ] # I don't usually recommend "inline if" statements in comprehensions # But if you decide you prefer them, I recommend parentheses for clarity shortened = [ (f"{name[:30 - 3]}..." if len(name) > 30 else name) for name in screencasts ] # I find this "inline if" formatting especially confusing # It looks like the "if" and "else" are part of the comprehension syntax shortened = [ f"{name[:30 - 3]}..." if len(name) > 30 else name for name in screencasts ] print(shortened)
219 views
Copy
Code copied
Run
in Browser
pym.dev/p/2zsh3/
URL copied
Need to share some Python code?
New Python snippet