๐ List Comprehensions
List comprehensions provide a concise way to create lists.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import time # 1. Basic list comprehension โ squares squares = [x**2 for x in range(1, 11)] print("Squares:", squares) # 2. Filtered comprehension pynfinity_scores = [45, 82, 91, 33, 77, 60, 55, 88, 71, 95] passing = [s for s in pynfinity_scores if s >= 60] print("Passing (โฅ60):", passing) # 3. Transformation + filter leaderboard = [{"name": "santoshtvk", "score": 95}, {"name": "dhruv", "score": 88}, {"name": "tvk", "score": 60}, {"name": "alice", "score": 45}] high_scorers = [u["name"].title() for u in leaderboard if u["score"] >= 70] print("High scorers:", high_scorers) # 4. Nested comprehension โ flatten matrix matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [val for row in matrix for val in row] print("Flattened:", flat) # 5. Dict comprehension course_map = {"Python": 95, "AI": 88, "DevOps": 72} boosted = {k: min(v + 5, 100) for k, v in course_map.items()} print("Boosted scores:", boosted) # 6. Set comprehension โ unique domains from emails emails = ["tvk@pynfinity.com", "dhruv@gmail.com", "a@pynfinity.com", "b@yahoo.com"] domains = {e.split("@")[1] for e in emails} print("Unique domains:", domains) # 7. Generator expression โ memory-efficient sum gen_sum = sum(x**2 for x in range(1_000_000)) # 8. Performance benchmark start = time.perf_counter() _ = [x**2 for x in range(100_000)] # List comp list_time = time.perf_counter() - start start = time.perf_counter() _ = list(map(lambda x: x**2, range(100_000))) # map + lambda map_time = time.perf_counter() - start print(f"\nList comp: {list_time*1000:.2f}ms | map(): {map_time*1000:.2f}ms")
Keep exploring and happy coding! ๐ป