What is list comprehension in Python and how does it work?
List comprehension is a concise way to create lists using a single line of code. It consists of an expression followed by a for clause and optional conditionals.
List comprehension in Python provides a syntactically compact and expressive way to create lists. It allows you to generate a new list by applying an expression to each item in an existing iterable, all in a single line of code. The general syntax is:
new_list = [expression for item in iterable if condition]
Here's a simple example that creates a list of squares for even numbers from 0 to 9:
squares = [x**2 for x in range(10) if x % 2 == 0]
In this case, expression
is x**2
, the for
clause iterates through range(10)
, and the if
clause filters out odd numbers. List comprehensions improve code readability and reduce the lines of code needed for list creation. They can also be nested, allowing for more complex operations, but it's essential to keep them readable. By using list comprehensions appropriately, you can write cleaner and more efficient Python code.