
Python List Comprehension: Complete Guide with Examples
List comprehensions are one of Python's most beloved features. They let you create lists in a single, readable line that would otherwise require a for loop and append calls. Beyond being more concise, comprehensions are often faster than equivalent loops because they're optimized at the C level in CPython. This guide covers everything from basic syntax to nested comprehensions, with the rules for when to use them and when not to. Basic Syntax The anatomy of a list comprehension: [ expression for item in iterable ] [ expression for item in iterable if condition ] Read it as: "give me expression for each item in iterable ". # Loop version squares = [] for x in range ( 10 ): squares . append ( x ** 2 ) # List comprehension — same result, one line squares = [ x ** 2 for x in range ( 10 )] print ( squares ) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # String transformations words = [ ' hello ' , ' world ' , ' python ' ] upper = [ word . upper () for word in words ] print ( upper ) # ['HELLO', '
Continue reading on Dev.to Webdev
Opens in a new tab




