List Comprehensions
List comprehensions provide a short and readable way to create a new list from an existing collection. They are very common in Python data processing and AI code.
A list comprehension creates a new list in one line.
Instead of writing several lines with a loop to build a list, you can often express the same logic using a simple list comprehension.
Why Do We Need List Comprehensions?
Suppose you have a list of numbers and you want to create another list containing their squares.
You could use a normal for loop.
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(number * number)
print(squares)
This works perfectly, but Python allows us to write the same operation more compactly.
Creating a List Comprehension
The same example can be written like this:
numbers = [1, 2, 3, 4, 5] squares = [number * number for number in numbers] print(squares)
The important part is:
[expression for item in collection]
Read it almost like English:
Take each number from numbers and calculate number * number and put the result into a new list.
Understand Each Part
Consider this code:
squares = [number * number for number in numbers]
It has three important parts.
| Part | Meaning |
|---|---|
| number * number | What value should be added to the new list? |
| for number | The variable used for each item |
| in numbers | The collection we are reading from |
So:
[number * number for number in numbers]
means: for every number in numbers, calculate its square and put the result into a new list.
Example: Processing AI Data
List comprehensions become useful when processing data. For example, suppose we have model confidence scores.
scores = [0.45, 0.72, 0.91, 0.63] percentages = [score * 100 for score in scores] print(percentages)
We took every score and converted it from a decimal into a percentage.
This type of simple transformation appears frequently when preparing data for AI applications.
List Comprehensions With a Condition
You can also use an if condition to decide
which values should be included.
For example, suppose we only want even numbers.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [
number
for number in numbers
if number % 2 == 0
]
print(even_numbers)
The condition:
if number % 2 == 0
means that only numbers divisible by 2 are added to the new list.
List comprehensions are a shorter way to create lists.
Start with the normal for-loop version first so you understand the logic. Then use a list comprehension when the operation is simple enough to remain readable. In AI and data processing, you will frequently use them to transform, filter, and prepare collections of data.