TGViewer
Python Learning Python Learning @python_bds · 5.74K subscribers
Post #1185 687
🐍 Python List Comprehensions (Concise Lists) ✨

List comprehensions provide a concise and elegant way to create lists. They allow you to build new lists by applying an expression to each item in an existing iterable, optionally with a condition.

🔹 1. What is a List Comprehension?

A single line of code to create a new list based on an existing sequence.

Syntax:
new_list = [expression for item in iterable if condition]

The if condition part is optional.

🔹 2. Basic List Comprehension

Creating a new list by transforming each item from an existing list or range.

Example (Squares):
numbers = [1, 2, 3, 4, 5]
squares = [num × num for num in numbers]
print(squares)

Output: [1, 4, 9, 16, 25]

Example (Uppercase names):
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names)

Output: ['ALICE', 'BOB', 'CHARLIE']

🔹 3. List Comprehension with Condition (if)

You can include an if clause to filter items, only including those that satisfy the condition.

Example (Even numbers):
all_numbers = range(10) # 0 to 9
even_numbers = [num for num in all_numbers if num % 2 == 0]
print(even_numbers)

Output: [0, 2, 4, 6, 8]

Example (Words starting with 'a'):
words = ["apple", "banana", "apricot", "cherry"]
a_words = [word for word in words if word.startswith('a')]
print(a_words)

Output: ['apple', 'apricot']

🔹 4. List Comprehension with if-else (Conditional Expression)

You can use an if-else expression within the expression part to choose a value based on a condition.

Syntax:
new_list = [expression_if_true if condition else expression_if_false for item in iterable]
Example:python
nums = [1, 2, 3, 4]
status = ["Even" if n % 2 == 0 else "Odd" for n in nums]
print(status)

Output: ['Odd', 'Even', 'Odd', 'Even']

🎯 Today's Goal

✔️ Understand the structure of list comprehensions
✔️ Create new lists from existing iterables
✔️ Filter items using if conditions
✔️ Use if-else for conditional value assignment
  • ❤ 3
  • 👍 1
  • 👏 1
More from @python_bds
  1. Oct 8, 2026🐛 This Python Bug Looks Random, But It Isn't Look at this: functions = [] for i in range(…
  2. Oct 6, 2026🐍 Python Performance Optimization Python Performance Optimization: Make Your Code Faster…
  3. Oct 4, 2026Python Set Methods ✍️
  4. Oct 3, 2026Post #1310
  5. Oct 1, 2026🐍 Python Beginner Notes
  6. Sep 30, 2026🧠 return vs print() in Python These are not interchangeable. def add(a, b): print(a + b)…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →