0% found this document useful (0 votes)
3 views2 pages

Python List Comprehensions & Decorators

The document provides examples of Python programming techniques including list comprehensions for generating squares and even numbers, the use of decorators to measure function execution time, and a context manager for file handling. It also demonstrates functional programming concepts with lambda functions for filtering, mapping, and reducing a list of numbers. Overall, it showcases various ways to write concise and efficient Python code.

Uploaded by

ourcodesare
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Python List Comprehensions & Decorators

The document provides examples of Python programming techniques including list comprehensions for generating squares and even numbers, the use of decorators to measure function execution time, and a context manager for file handling. It also demonstrates functional programming concepts with lambda functions for filtering, mapping, and reducing a list of numbers. Overall, it showcases various ways to write concise and efficient Python code.

Uploaded by

ourcodesare
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# Basic list comprehension

squares = [x**2 for x in range(10)]


# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With condition
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

#decorators

def timer(func):
def wrapper(*args, **kwargs):
import time
start = [Link]()
result = func(*args, **kwargs)
print(f"{func.__name__} took {[Link]() - start:.4f}s")
return result
return wrapper

@timer
def slow_function():
[Link](1)
return "Done"

slow_function() # Prints execution time

class FileManager:
def __init__(self, filename, mode):
[Link] = filename
[Link] = mode

def __enter__(self):
[Link] = open([Link], [Link])
return [Link]

def __exit__(self, exc_type, exc_val, exc_tb):


[Link]()

with FileManager('[Link]', 'w') as f:


[Link]('Hello World')

numbers = [1, 2, 3, 4, 5, 6]

# Filter with lambda


evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4, 6]

# Map with lambda


squared = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25, 36]

# Reduce
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
# 720

You might also like