Python – List Comprehension

1. What is List Comprehension?

List comprehension is a short and easy way to create a new list from an existing list.

In simple words:
๐Ÿ‘‰ It lets you write less code to do the same work.

2. Normal Way vs List Comprehension

Normal Way (Using Loop)

numbers = [1, 2, 3, 4]
new_numbers = []

for n in numbers:
new_numbers.append(n * 2)

print(new_numbers)

List Comprehension Way

numbers = [1, 2, 3, 4]
new_numbers = [n * 2 for n in numbers]

print(new_numbers)

๐Ÿ‘‰ Both give the same result, but list comprehension is shorter.

3. Basic Syntax (Easy)

new_list = [expression for item in old_list]

4. Simple Example

Example

fruits = ["apple", "banana", "orange"]

new_list = [fruit for fruit in fruits]

print(new_list)

5. List Comprehension with Condition

You can add a condition using if.

Example

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = [n for n in numbers if n % 2 == 0]

print(even_numbers)

6. Change Values Using List Comprehension

Example

names = ["amit", "ravi", "sita"]

new_names = [name.upper() for name in names]

print(new_names)

7. List Comprehension with String

Example

text = "hello"

letters = [ch for ch in text]

print(letters)

8. List Comprehension with Numbers

Example

numbers = [10, 20, 30]

new_list = [n + 5 for n in numbers]

print(new_list)

9. Using ifโ€“else in List Comprehension

Example

numbers = [1, 2, 3, 4]

result = ["even" if n % 2 == 0 else "odd" for n in numbers]

print(result)

10. Common Beginner Mistakes

โŒ Forgetting Brackets

new_list = n * 2 for n in numbers

โœ” Correct:

new_list = [n * 2 for n in numbers]

โŒ Making It Too Complex

Avoid very long list comprehensions at the beginning.

11. Simple Practice Examples

Example 1: Square Numbers

nums = [1, 2, 3, 4]

squares = [n * n for n in nums]
print(squares)

Example 2: Names with Letter A

names = ["Amit", "Ravi", "Anita"]

a_names = [name for name in names if "A" in name]
print(a_names)

Example 3: Convert to String

numbers = [1, 2, 3]

strings = [str(n) for n in numbers]
print(strings)

12. Summary (List Comprehension)

โœ” Short way to create lists
โœ” Cleaner than loops
โœ” Can use conditions
โœ” Easy to read if simple
โœ” Very useful in Python

๐Ÿ“˜ Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Sort Lists

  • Copy Lists

  • Join Lists

  • Tuple Basics

  • List Exercises

Just tell me ๐Ÿ˜Š

You may also like...