shreyiot
Member
List comprehension in Python is a concise way to create lists using a single line of code. It enhances readability and reduces the need for traditional for loops, making the code more efficient and Pythonic.
The general syntax for list comprehension is:
python
CopyEdit
new_list = [expression for item in iterable if condition]
python
CopyEdit
squares = [x**2 for x in range(1, 6)]
print(squares)
Output: [1, 4, 9, 16, 25]
python
CopyEdit
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
Output: [0, 2, 4, 6, 8]
python
CopyEdit
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words)
Output: ['HELLO', 'WORLD', 'PYTHON']
List comprehension is a powerful feature that every Python programmer should master. If you want to learn Python from scratch, consider Python training in Noida to build strong programming skills.
Syntax of List Comprehension:
The general syntax for list comprehension is:
python
CopyEdit
new_list = [expression for item in iterable if condition]
- expression: The operation to be performed on each element.
- item: The element taken from the iterable.
- iterable: The source from which elements are extracted (like a list, tuple, or range).
- condition (optional): A filtering criterion to include only specific elements.
Example 1: Creating a List of Squares
python
CopyEdit
squares = [x**2 for x in range(1, 6)]
print(squares)
Output: [1, 4, 9, 16, 25]
Example 2: Filtering Even Numbers
python
CopyEdit
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
Output: [0, 2, 4, 6, 8]
Example 3: Transforming Strings
python
CopyEdit
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words)
Output: ['HELLO', 'WORLD', 'PYTHON']
Advantages of List Comprehension
- Concise & Readable: Reduces multiple lines of code into one.
- Faster Execution: More efficient than traditional loops.
- Memory Efficient: Works well with generators and large datasets.
List comprehension is a powerful feature that every Python programmer should master. If you want to learn Python from scratch, consider Python training in Noida to build strong programming skills.