Python List Comprehension
Python List Comprehension is a core Python concept covering python List Comprehension: List comprehension offers a shorter syntax This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Syntax
newlist = [expression for item in iterable if condition == True]
Example
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
Without list comprehension:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
With list comprehension:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
More Examples
- No condition:
[x for x in fruits] - Iterable:
[x for x in range(10)] - Expression:
[x.upper() for x in fruits] - If-Else:
[x if x != "banana" else "orange" for x in fruits]
Readability
List comprehension is very "Pythonic" and clean, but don't make them too complex or they become hard to read!