PYTHON

Efficient List Filtering and Transformation with List Comprehensions

Learn to concisely filter and transform Python lists using list comprehensions. This snippet demonstrates how to create new lists based on conditions or modifications of existing elements, a powerful and readable technique for data manipulation.

# Original list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 1. Filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
print(f"Even numbers: {even_numbers}")

# 2. Transform numbers (e.g., square them)
squared_numbers = [num ** 2 for num in numbers]
print(f"Squared numbers: {squared_numbers}")

# 3. Filter and transform in one go
even_squared_numbers = [num ** 2 for num in numbers if num % 2 == 0]
print(f"Even numbers squared: {even_squared_numbers}")

# 4. Using list comprehensions with strings
words = ["apple", "banana", "cherry", "date"]
long_words = [word.upper() for word in words if len(word) > 5]
print(f"Long words (uppercased): {long_words}")
How it works: List comprehensions provide a concise way to create lists. They consist of brackets containing an expression followed by a `for` clause, then zero or more `for` or `if` clauses. They offer a more readable and often faster alternative to `for` loops and `filter()`/`map()` functions for building new lists based on existing iterables, allowing for both filtering (with `if` conditions) and transformation (with expressions) in a single line.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs