List Comprehension in Python
×

List Comprehension in Python

120

List Comprehension in Python

Python's list comprehension provides a concise way to create lists. It allows for the generation of new lists by applying an expression to each item in an existing iterable, optionally filtering elements based on a condition.

Basic Syntax

The general syntax of a list comprehension is:

[expression for item in iterable if condition]
  • expression: The value to store in the new list.
  • item: The current element from the iterable.
  • iterable: A sequence (e.g., list, tuple, range).
  • condition (optional): A filter that determines whether the item is included.

List Comprehension vs. Traditional for Loop

Consider doubling each number in a list:

Using a for loop:

numbers = [1, 2, 3, 4, 5]
doubled = []
for n in numbers:
    doubled.append(n * 2)
print(doubled)  # Output: [2, 4, 6, 8, 10]

Using list comprehension:

numbers = [1, 2, 3, 4, 5]
doubled = [n * 2 for n in numbers]
print(doubled)  # Output: [2, 4, 6, 8, 10]

List comprehension achieves the same result with more concise and readable code.

Incorporating Conditions

You can include conditions to filter elements. For example, to extract even numbers:

numbers = [1, 2, 3, 4, 5]
evens = [n for n in numbers if n % 2 == 0]
print(evens)  # Output: [2, 4]

Using if-else in List Comprehension

List comprehensions can also include an if-else statement:

numbers = [1, 2, 3, 4, 5]
labels = ['Even' if n % 2 == 0 else 'Odd' for n in numbers]
print(labels)  # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']

Nested Loops in List Comprehension

List comprehensions can include nested loops. For example, creating coordinate pairs:

coords = [(x, y) for x in range(3) for y in range(3)]
print(coords)  # Output: [(0, 0), (0, 1), (0, 2), (1, 0), ..., (2, 2)]

Flattening a List of Lists

To flatten a nested list:

matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)  # Output: [1, 2, 3, 4, 5, 6]

Conclusion

List comprehensions in Python offer a powerful and concise way to create and manipulate lists. By integrating loops and conditional logic into a single line, they enhance code readability and efficiency.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat