PYTHON

Concise Data Transformation with List Comprehensions

Master Python list comprehensions to create new lists from existing iterables with filtering and transformation, offering a readable and efficient alternative to traditional loops.

# Basic list comprehension: square numbers
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(f"Squares: {squares}")

# List comprehension with filtering: even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
print(f"Even numbers: {even_numbers}")

# List comprehension with transformation and filtering: uppercase names starting with 'J'
names = ['Alice', 'Bob', 'John', 'Jane', 'Charlie']
j_names_upper = [name.upper() for name in names if name.startswith('J')]
print(f"J-names uppercase: {j_names_upper}")

# Dictionary comprehension for creating dictionaries
# {'key': 'value'} -> {'KEY': 'VALUE'}
original_dict = {'a': 1, 'b': 2, 'c': 3}
transformed_dict = {k.upper(): v * 10 for k, v in original_dict.items() if v > 1}
print(f"Transformed dictionary: {transformed_dict}")
How it works: List comprehensions provide a concise and expressive way to create new lists (or sets, dictionaries) based on existing iterables. They consist of an expression followed by a `for` clause, and optionally an `if` clause for filtering. This syntax often makes code more readable and efficient compared to traditional `for` loops, especially for simple transformations and filtering operations on data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs