What is List Comprehension in Python: Simple Explanation and Example
list comprehension is a concise way to create lists by writing a single expression inside square brackets. It lets you generate a new list by applying an operation to each item in an existing list or iterable, often replacing longer loops with simpler code.How It Works
List comprehension works like a recipe that tells Python how to build a new list step-by-step. Imagine you have a basket of apples and you want to make a basket of apple slices. Instead of slicing each apple one by one and putting the slices in a new basket, list comprehension lets you describe the slicing process in one quick instruction.
It combines a loop and an expression in one line: the loop goes through each item in the original list, and the expression tells what to do with each item before adding it to the new list. This makes your code shorter and easier to read, like writing a quick note instead of a long letter.
Example
This example creates a list of squares of numbers from 1 to 5 using list comprehension.
squares = [x ** 2 for x in range(1, 6)] print(squares)
When to Use
Use list comprehension when you want to create a new list by transforming or filtering items from another list or iterable. It is great for simple tasks like squaring numbers, converting strings to uppercase, or selecting only certain items based on a condition.
For example, if you have a list of temperatures in Celsius and want to convert them to Fahrenheit, list comprehension makes this quick and clean. It helps keep your code neat and easy to understand, especially when the operation is straightforward.
Key Points
- List comprehension is a compact way to create lists in one line.
- It combines a loop and an expression inside square brackets.
- It can include conditions to filter items.
- It makes code shorter and more readable compared to traditional loops.