List comprehensions in Details From Start to End
A list comprehension is a concise way to create lists in Python. It follows the patte
✅Pattern 1: Basic List Comprehension
[expression for item in iterable if condition]
Breaking it Down:
1️⃣ Expression → What to do with each item in the list.
2️⃣ Iterable → The source (e.g., list, range(), df.columns, etc.).
3️⃣ Condition (Optional) → A filter to select items that meet certain criteria.
✅Pattern 2: List Comprehension with if-else (Ternary Expression)
[expression_if_true if condition else expression_if_false for item in iterable]
Common Mistake
❌ Incorrect (if placed incorrectly)
[x**2 for x in numbers if x % 2 == 0 else x**3] # ❌ SyntaxError
✅ Correct (if-else goes before for in ternary case)
[x**2 if x % 2 == 0 else x**3 for x in numbers] # ✅ Works fine
✅ Pattern 3: Nested List Comprehensions
[expression for sublist in iterable for item in sublist]
Here’s a comprehensive collection of list comprehension examples, including basic, advanced, and smart/tricky ones:
🔥 Basic List Comprehension Examples
1️⃣ Square of Numbers
squares = [x**2 for x in range(5)]
print(squares)
# Output: [0, 1, 4, 9, 16]
2️⃣ Filtering Even Numbers
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
# Output: [0, 2, 4, 6, 8]
3️⃣ Labeling Odd and Even Numbers
labels = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(labels)
# Output: ['Even', 'Odd', 'Even', 'Odd', 'Even']
🚀 Smart List Comprehension Examples
4️⃣ Removing _n
from Column Names
columns = ["col_1", "col_2", "name", "col_119"]
clean_columns = [col.replace("_" + col.split("_")[-1], "") if col.split("_")[-1].isdigit() else col for col in columns]
print(clean_columns)
# Output: ['col', 'col', 'name', 'col']
5️⃣ Flatten a List of Lists
matrix = [[1, 2, 3], [4, 5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened)
# Output: [1, 2, 3, 4, 5, 6]
6️⃣ Square Even Numbers, Cube Odd Numbers
numbers = range(1, 11)
result = [x**2 if x % 2 == 0 else x**3 for x in numbers]
print(result)
# Output: [1, 4, 27, 16, 125, 36, 343, 64, 729, 100]
7️⃣ Filtering Multiples of 3 and Incrementing Odd Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = [x + 1 if x % 2 != 0 else x for x in numbers if x % 3 == 0]
print(result)
# Output: [4, 7, 10]
8️⃣ Creating Labels for Word Lengths
words = ["apple", "banana", "grape", "watermelon", "orange"]
result = [f"{word}: long" if len(word) > 6 else f"{word}: short" for word in words]
print(result)
# Output: ['apple: short', 'banana: short', 'grape: short', 'watermelon: long', 'orange: short']
💡 Tricky and Useful List Comprehension Examples
9️⃣ Extracting Digits from Strings
data = ["a12", "b3c", "45d", "xyz"]
digits = ["".join([char for char in item if char.isdigit()]) for item in data]
print(digits)
# Output: ['12', '3', '45', '']
🔟 Finding Common Elements in Two Lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common = [x for x in list1 if x in list2]
print(common)
# Output: [3, 4, 5]
1️⃣1️⃣ Finding Unique Elements in One List (Not in Another)
unique = [x for x in list1 if x not in list2]
print(unique)
# Output: [1, 2]
1️⃣2️⃣ Generate Pairs of Numbers (Tuple Pairing)
pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)
# Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
1️⃣3️⃣ Creating a Dictionary Using List Comprehension
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
1️⃣4️⃣ Finding Duplicate Elements in a List
nums = [1, 2, 3, 2, 4, 5, 6, 4, 7]
duplicates = list(set([x for x in nums if nums.count(x) > 1]))
print(duplicates)
# Output: [2, 4]
1️⃣5️⃣ Converting a List of Strings to Integers, Ignoring Errors
data = ["10", "abc", "30", "xyz", "50"]
numbers = [int(x) for x in data if x.isdigit()]
print(numbers)
# Output: [10, 30, 50]
1️⃣6️⃣ Getting the ASCII Values of Characters
ascii_values = [ord(char) for char in "Python"]
print(ascii_values)
# Output: [80, 121, 116, 104, 111, 110]
🔥 Bonus: Nested List Comprehension
1️⃣7️⃣ Transposing a Matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed)
# Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
1️⃣8️⃣ Flattening a Nested Dictionary
data = {"a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}}
flattened = [(key, subkey, value) for key, subdict in data.items() for subkey, value in subdict.items()]
print(flattened)
# Output: [('a', 'x', 1), ('a', 'y', 2), ('b', 'x', 3), ('b', 'y', 4)]
Discover more from HintsToday
Subscribe to get the latest posts sent to your email.