PYTHON FOR AI • LESSON 1

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.

CORE IDEA

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.

01

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)
Output: [1, 4, 9, 16, 25]

This works perfectly, but Python allows us to write the same operation more compactly.

02

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)
Output: [1, 4, 9, 16, 25]

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.
03

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.

04

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)
Output: [45.0, 72.0, 91.0, 63.0]

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.

05

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)
Output: [2, 4, 6]

The condition:

if number % 2 == 0

means that only numbers divisible by 2 are added to the new list.

KEY TAKEAWAY

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.