In the previous lesson, you learned how to create, modify, and manage Python lists using various built-in methods. Although these methods are powerful, there are situations where creating a new list using a loop requires several lines of code. Python provides a more elegant and efficient solution called List Comprehension.
List comprehension allows you to create new lists in a single line of code. It is one of Python’s most popular features because it makes programs shorter, cleaner, and easier to read. Data analysts, machine learning engineers, automation developers, and software engineers frequently use list comprehensions to process data efficiently.
In this lesson, you will learn what list comprehension is, why it is useful, its syntax, how it compares to traditional loops, and how to create lists using the range() function.
After completing this lesson, you will be able to:
range() function with list comprehension.List comprehension is a concise way to create a new list by applying an expression to each element of an iterable such as a list, tuple, string, or range.
Instead of writing multiple lines using a for loop, list comprehension performs the same task in a single line.
new_list = [expression for item in iterable]
The syntax contains three parts:
List comprehension makes programs shorter, cleaner, and often faster than traditional loops.
It is commonly used for:
Suppose you want to create a list containing the squares of numbers from 1 to 5.
squares = []
for number in range(1, 6):
squares.append(number ** 2)
print(squares)
Output
[1, 4, 9, 16, 25]
The program creates an empty list, iterates through each number, calculates the square, and appends it to the list.
squares = [number ** 2 for number in range(1, 6)]
print(squares)
Output
[1, 4, 9, 16, 25]
The same result is achieved in a single line of code.
List comprehension can copy elements from an existing list.
numbers = [10, 20, 30, 40]
new_numbers = [num for num in numbers]
print(new_numbers)
Output
[10, 20, 30, 40]
Each element from the original list is copied into the new list.
The expression can perform calculations before storing each value.
numbers = [1, 2, 3, 4, 5]
doubles = [num * 2 for num in numbers]
print(doubles)
Output
[2, 4, 6, 8, 10]
Each number is multiplied by 2 before being added to the new list.
range() with List ComprehensionThe range() function is commonly used to generate sequences of numbers.
numbers = [x for x in range(1, 11)]
print(numbers)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range()squares = [x ** 2 for x in range(1, 6)]
print(squares)
Output
[1, 4, 9, 16, 25]
List comprehension also works with string data.
languages = ["python", "java", "c++"]
uppercase = [lang.upper() for lang in languages]
print(uppercase)
Output
['PYTHON', 'JAVA', 'C++']
The upper() method converts each string to uppercase before storing it.
You can transform values while creating a new list.
prices = [500, 750, 1000]
discounted = [price - 100 for price in prices]
print(discounted)
Output
[400, 650, 900]
This technique is useful when processing datasets.
Consider the following program.
numbers = [x * 3 for x in range(1, 5)]
print(numbers)
Execution Steps
1, 2, 3, 4 using range().x receives one value at a time.3.numbers.Output
[3, 6, 9, 12]
List comprehensions must always be enclosed within [].
The correct order is:
[expression for item in iterable]
If a list comprehension becomes difficult to read, a traditional for loop may be a better choice.
List comprehension creates a new list and does not modify the original list unless it is reassigned.
List comprehensions use square brackets ([]), whereas generator expressions use parentheses (()).
In this section, you learned what Python list comprehension is and why it is a popular feature for creating lists efficiently. You explored its syntax, compared it with traditional for loops, created lists from existing data, applied mathematical operations, used the range() function, transformed string values, and examined its execution flow and advantages. You also reviewed common beginner mistakes. In the next section, you will learn how to use conditions inside list comprehensions, including if, if...else, multiple conditions, and practical filtering examples.
In the previous section, you learned how to create new lists using list comprehension. While creating lists is useful, Python becomes even more powerful when you combine list comprehensions with conditions. This allows you to filter data, transform selected values, and create customized lists using a single line of code.
Conditional list comprehensions are widely used in data analysis, automation, web development, and machine learning because they make data filtering simple and efficient.
if in List ComprehensionYou can add an if condition to include only elements that satisfy a specific condition.
new_list = [expression for item in iterable if condition]
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
Output
[2, 4, 6]
Only the even numbers are added to the new list.
numbers = [1, 2, 3, 4, 5, 6]
odd_numbers = [num for num in numbers if num % 2 != 0]
print(odd_numbers)
Output
[1, 3, 5]
if...else in List ComprehensionYou can use if...else to return different values based on a condition.
new_list = [value_if_true if condition else value_if_false for item in iterable]
numbers = [1, 2, 3, 4, 5]
result = ["Even" if num % 2 == 0 else "Odd" for num in numbers]
print(result)
Output
['Odd', 'Even', 'Odd', 'Even', 'Odd']
The expression labels each number as Even or Odd.
Multiple conditions can be combined using logical operators such as and and or.
numbers = range(1, 21)
result = [num for num in numbers if num % 2 == 0 and num > 10]
print(result)
Output
[12, 14, 16, 18, 20]
Only numbers that satisfy both conditions are included.
List comprehension can filter strings based on their length or content.
languages = ["Python", "C", "Java", "Go", "JavaScript"]
long_names = [lang for lang in languages if len(lang) > 4]
print(long_names)
Output
['Python', 'Java', 'JavaScript']
languages = ["python", "java", "c++"]
uppercase = [lang.upper() for lang in languages]
print(uppercase)
Output
['PYTHON', 'JAVA', 'C++']
The expression part can perform calculations while creating the list.
numbers = [5, 10, 15, 20]
tax = [price * 1.18 for price in numbers]
print(tax)
Output
[5.9, 11.8, 17.7, 23.6]
List comprehension can clean unwanted values from a list.
names = ["Rahul", "", "Priya", "", "Amit"]
clean_names = [name for name in names if name != ""]
print(clean_names)
Output
['Rahul', 'Priya', 'Amit']
Suppose you want to identify students who scored more than 80 marks.
marks = [75, 82, 90, 67, 88, 79]
top_students = [mark for mark in marks if mark >= 80]
print(top_students)
Output
[82, 90, 88]
prices = [100, 250, 400, 800]
discounted = [price - 50 if price > 200 else price for price in prices]
print(discounted)
Output
[100, 200, 350, 750]
Consider the following program.
numbers = [1, 2, 3, 4, 5, 6]
even = [num for num in numbers if num % 2 == 0]
print(even)
Execution Steps
num % 2 == 0 is evaluated.even.Output
[2, 4, 6]
if in the Wrong PositionThe filtering condition must appear after the for clause.
if...elseA filtering if removes elements, while if...else replaces values.
Use parentheses where necessary to improve readability.
If the expression becomes difficult to understand, use a traditional for loop instead.
List comprehensions return a new list without changing the original list unless it is reassigned.
In this section, you learned how to use conditions inside Python list comprehensions. You explored filtering with if, transforming values using if...else, combining multiple conditions, processing string lists, performing mathematical calculations, cleaning data, and solving practical problems such as filtering student marks and applying discounts. You also reviewed the execution flow and common beginner mistakes. In the next section, you will learn advanced list comprehension techniques, including nested list comprehensions, flattening nested lists, using functions, combining multiple loops, performance comparisons, and real-world applications.
In the previous section, you learned how to use conditions inside list comprehensions to filter and transform data. List comprehensions become even more powerful when they are combined with nested loops, functions, and multiple iterables. These advanced techniques are commonly used in data analysis, automation, and scientific computing to write efficient and readable code.
In this section, you will explore advanced list comprehension techniques, including nested list comprehensions, flattening nested lists, using functions, combining multiple loops, performance considerations, and real-world examples.
A nested list comprehension contains one for loop inside another. It is commonly used to process two-dimensional data.
[expression for outer_item in outer_iterable for inner_item in inner_iterable]
pairs = [(x, y) for x in range(1, 4) for y in range(1, 3)]
print(pairs)
Output
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]
The outer loop selects each value of x, while the inner loop generates every value of y.
Sometimes data is stored as a list of lists. List comprehension can flatten it into a single list.
matrix = [
[1, 2],
[3, 4],
[5, 6]
]
flat = [item for row in matrix for item in row]
print(flat)
Output
[1, 2, 3, 4, 5, 6]
This technique is widely used when working with tables and datasets.
The expression can call functions while creating the list.
names = ["rahul", "priya", "amit"]
formatted = [name.title() for name in names]
print(formatted)
Output
['Rahul', 'Priya', 'Amit']
The title() method capitalizes the first letter of each name.
numbers = [1, 2, 3, 4, 5]
squares = [pow(num, 2) for num in numbers]
print(squares)
Output
[1, 4, 9, 16, 25]
List comprehension can generate combinations from multiple iterables.
colors = ["Red", "Blue"]
sizes = ["S", "M", "L"]
products = [color + "-" + size
for color in colors
for size in sizes]
print(products)
Output
['Red-S', 'Red-M', 'Red-L',
'Blue-S', 'Blue-M', 'Blue-L']
This approach is useful when generating combinations of data.
pairs = [(x, y)
for x in range(1, 6)
for y in range(1, 6)
if x == y]
print(pairs)
Output
[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
The condition filters the generated combinations.
List comprehensions are generally faster than traditional for loops because Python performs the iteration internally.
squares = []
for num in range(1000):
squares.append(num ** 2)
squares = [num ** 2 for num in range(1000)]
Both programs produce the same result, but the list comprehension is shorter and usually executes faster.
scores = [95, None, 82, None, 76, 91]
clean_scores = [score for score in scores if score is not None]
print(clean_scores)
Output
[95, 82, 76, 91]
This technique is frequently used to remove missing values from datasets.
users = ["rahul", "priya", "amit"]
emails = [user + "@gmail.com" for user in users]
print(emails)
Output
['rahul@gmail.com',
'priya@gmail.com',
'amit@gmail.com']
celsius = [0, 10, 20, 30]
fahrenheit = [(temp * 9/5) + 32 for temp in celsius]
print(fahrenheit)
Output
[32.0, 50.0, 68.0, 86.0]
Consider the following program.
numbers = [num ** 2 for num in range(1, 6)]
print(numbers)
Execution Steps
1 to 5.num.num ** 2 is evaluated.Output
[1, 4, 9, 16, 25]
for loop for complex logic.Long expressions reduce readability and make debugging difficult.
The order of for clauses affects the generated output.
List comprehensions return a new list without modifying the original list.
Avoid repeatedly calling slow functions inside list comprehensions when the result can be reused.
If you only need to iterate over values without storing them, a normal for loop or a generator expression may be more appropriate.
In this section, you learned advanced Python list comprehension techniques. You explored nested list comprehensions, flattened nested lists, used functions inside comprehensions, combined multiple loops, applied conditions, compared performance with traditional loops, and solved practical problems such as data cleaning, email generation, and temperature conversion. You also reviewed best practices and common beginner mistakes. In the final section, you will summarize the lesson with key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python Tuples: Complete Guide for Beginners.
In this lesson, you learned how Python List Comprehension provides a concise and efficient way to create new lists. Instead of writing multiple lines using traditional for loops, list comprehension allows you to perform the same task in a single, readable statement.
You began by understanding the syntax of list comprehension and learned how it compares with traditional loops. You created new lists from existing data, used the range() function, and applied mathematical operations while generating lists.
Next, you explored conditional list comprehensions using if and if...else statements. You learned how to filter data, apply multiple conditions, transform string values, and solve practical problems such as selecting top-performing students and applying discounts.
Finally, you studied advanced techniques including nested list comprehensions, flattening nested lists, using functions inside comprehensions, combining multiple loops, and understanding performance advantages. You also reviewed best practices and common beginner mistakes.
List comprehension is widely used in data analysis, machine learning, automation, scientific computing, and software development because it produces clean, readable, and efficient Python code.
[expression for item in iterable].for loops.range() function is commonly used with list comprehension.if statement filters elements while creating a new list.if...else expression transforms values based on conditions.and and or.List comprehension is a concise way to create a new list by applying an expression to each element of an iterable.
It reduces the number of lines of code, improves readability, and often provides better performance.
for loop?No. It is best suited for simple list creation and filtering. Complex logic is often easier to understand using traditional loops.
Yes. You can use if for filtering and if...else for conditional expressions.
Yes. It can transform, filter, and manipulate string data.
It is a list comprehension containing multiple for loops, commonly used for processing nested lists.
No. It creates a new list unless the result is assigned back to the original variable.
Yes. Built-in functions and string methods can be used in the expression.
In many cases, yes. List comprehensions are generally more efficient because Python optimizes their execution.
Avoid using it when the expression becomes too complex and reduces code readability.
range() loops.@gmail.com to a list of usernames.if condition inside list comprehension?if...else.Create a Python program that analyzes student marks using list comprehension.
Your program should:
if...else.========== STUDENT MARKS ANALYZER ==========
Original Marks
[75, 82, 90, 67, 88, 79]
Top Students
[82, 90, 88]
Grades
['Pass', 'Pass', 'Pass', 'Fail', 'Pass', 'Pass']
Bonus Marks
[80, 87, 95, 72, 93, 84]
Students Above 80 : 3
============================================
Congratulations! You have successfully learned Python List Comprehension. You now understand how to create lists efficiently, apply conditions, filter data, transform values, work with nested list comprehensions, flatten nested structures, and use functions inside comprehensions.
In the next lesson, you will begin a new section: Python Tuples: Complete Guide for Beginners. You will learn what tuples are, how they differ from lists, how to create and access tuple elements, tuple packing and unpacking, tuple methods, and practical real-world examples.