Back to articles
Python List Comprehensions Explained Simply (Concise Syntax)

Python List Comprehensions Explained Simply (Concise Syntax)

via Dev.to TutorialShahrouz Nikseresht

List comprehensions provide a short and readable way to create new lists based on existing ones. They combine loops and conditions in one line. What is a list comprehension? A basic list comprehension looks like this: numbers = [ 1 , 2 , 3 , 4 , 5 ] squares = [ x * x for x in numbers ] print ( squares ) # [1, 4, 9, 16, 25] The structure is: [new_value for item in sequence] It works like a for loop but written inside square brackets. Adding conditions Filter items with an if clause: even_squares = [ x * x for x in numbers if x % 2 == 0 ] print ( even_squares ) # [4, 16] Only items where the condition is True are included. More examples Double values greater than 3: doubled = [ x * 2 for x in numbers if x > 3 ] print ( doubled ) # [8, 10] Convert strings to uppercase: words = [ " hello " , " world " , " python " ] upper = [ word . upper () for word in words ] print ( upper ) # ['HELLO', 'WORLD', 'PYTHON'] Replace values conditionally: adjusted = [ x + 1 if x < 3 else x - 1 for x in numbe

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles