ๆƒฏๆ€ง่šๅˆ ้ซ˜ๆ•ˆ่ฟฝ่ธชๅ’Œ้˜…่ฏปไฝ ๆ„Ÿๅ…ด่ถฃ็š„ๅšๅฎขใ€ๆ–ฐ้—ปใ€็ง‘ๆŠ€่ต„่ฎฏ
้˜…่ฏปๅŽŸๆ–‡ ๅœจๆƒฏๆ€ง่šๅˆไธญๆ‰“ๅผ€

ๆŽจ่่ฎข้˜…ๆบ

D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
Scott Helme
Scott Helme
Know Your Adversary
Know Your Adversary
NISL@THU
NISL@THU
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet โ€“ Hacking Tools, Hacker News & Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Schneier on Security
I
Intezer
Spread Privacy
Spread Privacy
AWS News Blog
AWS News Blog
V
Vulnerabilities โ€“ Threatpost
Cloudbric
Cloudbric
V2EX - ๆŠ€ๆœฏ
V2EX - ๆŠ€ๆœฏ
Google Online Security Blog
Google Online Security Blog
L
Lohrmann on Cybersecurity
Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LINUX DO - ็ƒญ้—จ่ฏ้ข˜
S
Secure Thoughts
T
The Exploit Database - CXSecurity.com
ๅš
ๅšๅฎขๅ›ญ - ใ€ๅฝ“่€็‰นใ€‘
Recent Announcements
Recent Announcements
Security Archives - TechRepublic
Security Archives - TechRepublic
Stack Overflow Blog
Stack Overflow Blog
็ฝ—
็ฝ—็ฃŠ็š„็‹ฌ็ซ‹ๅšๅฎข
OSCHINA ็คพๅŒบๆœ€ๆ–ฐๆ–ฐ้—ป
OSCHINA ็คพๅŒบๆœ€ๆ–ฐๆ–ฐ้—ป
K
Kaspersky official blog
้˜ฎไธ€ๅณฐ็š„็ฝ‘็ปœๆ—ฅๅฟ—
้˜ฎไธ€ๅณฐ็š„็ฝ‘็ปœๆ—ฅๅฟ—
ๅš
ๅšๅฎขๅ›ญ_้ฆ–้กต
Latest news
Latest news
B
Blog
F
Full Disclosure
ๅคง็Œซ็š„ๆ— ้™ๆธธๆˆ
ๅคง็Œซ็š„ๆ— ้™ๆธธๆˆ
ๅš
ๅšๅฎขๅ›ญ - ๅถๅฐ้’—
L
LangChain Blog
GbyAI
GbyAI
Last Week in AI
Last Week in AI
S
Security Affairs
Apple Machine Learning Research
Apple Machine Learning Research
N
Netflix TechBlog - Medium
Security Latest
Security Latest
Vercel News
Vercel News
Y
Y Combinator Blog
G
GRAHAM CLULEY
S
Securelist
T
Troy Hunt's Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
้›ทๅณฐ็ฝ‘
้›ทๅณฐ็ฝ‘

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Donโ€™t Fail โ€” They Drift Spilling beans for how i learn for exam๐Ÿ˜"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" โ€” What Actually Happened Comfy Cloudโ€™s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions โ€” here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components โ€” Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cรณmo construรญ un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 ๐Ÿš€ I Built an Ethical Hacking Scanner Tool โ€“ Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points โ€” Here's What I Found About How Markets Really Move EcoTrack AI โ€” Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead โ€” I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve โ€” no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like Youโ€™re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace โ€” how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025โ€“62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D โ€” A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent โ€” It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly โ€” 2026/04/10โ€“04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI ้€ฑๅ ฑ โ€” 2026/04/10โ€“2026/04/17 ๆจกๅž‹ๅฐ้Ž–ๆฝฎไพ†ไบ†๏ผŒไฝ†ๅทฅๅ…ท้ˆๆ‰ๆ˜ฏ็œŸๆˆฐๅ ด Maybe this is how Open-Source apps are born... ๐Ÿš€ Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge โ€” $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase โ€” Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train โ€” Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extraรงรฃo de Vรญdeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life โ€” Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 โ€” Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows โ€” Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTrackingๅฎ‰่ฃ…ๅ’ŒiPhone้ขๆ•้…็ฝฎๆ•™็จ‹๏ผŒๆœ‰bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Functions, Scope (Local/Global), Arguments, return, Lambda, filter()/map()/reduce(), Modules
Tejas Shinkar ยท 2026-06-21 ยท via DEV Community

๐Ÿ“Œ Key Concepts Overview

Concept One-Line Definition
Function A reusable, named block of code that runs when called
Parameter vs Argument Parameter = name in definition. Argument = value passed at call time
Local variable Exists only inside the function it's defined in
Global variable Exists outside any function, accessible everywhere
global keyword Lets a function modify a global variable
return Sends a value back from the function and ends it
*args Collects extra positional arguments into a tuple
**kwargs Collects extra keyword arguments into a dict
lambda A small, unnamed (anonymous) one-line function
filter() Keeps only elements that satisfy a condition
map() Applies an operation to every element
reduce() Aggregates an iterable into a single value
Module A .py file containing reusable functions/classes

๐Ÿงฉ Part 1 โ€” Why Functions?

# WITHOUT a function โ€” code duplicated everywhere
a, b = 10, 20
print(a + b)
str1 = input('Enter a string: ')
if str1 == str1[::-1]:
    print('Palindrome')

# ... later in the program, same logic copy-pasted again ...

Functions exist to:

  • Avoid repeating code (write once, call many times)
  • Reduce program size
  • Organize logic into reusable, testable units
def add(a, b):
    c = a + b
    print(c)

def is_palindrome():
    str1 = input('Enter a string: ')
    if str1 == str1[::-1]:
        print('Palindrome')
    else:
        print('Not a Palindrome')

# Now reuse anywhere:
add(327, 46)
is_palindrome()

Two Types of Functions

Type Example
In-built (Python provides) print(), len(), type(), input()
User-defined (you write) def add(a, b): ...

The 2 Components of Every Function

  1. Function Definition โ€” written using def, contains the logic. Does NOT run on its own.
  2. Function Call โ€” function_name() โ€” this is what actually executes the code.
def add():            # โ† definition (just creates it, doesn't run it)
    print('Hello')

add()                  # โ† call (THIS runs it)


โš ๏ธ Don't Shadow Built-in Functions (Recap + New Example)

# โŒ DANGEROUS โ€” overwrites Python's built-in print/len
def print():
    print('Hello')      # this would now infinitely recurse / break

def len():
    print('Hello')

len('Python')            # โŒ TypeError โ€” len() no longer works as expected,
                          # it now expects ZERO arguments because you redefined it

Lesson: Never name your functions print, len, list, input, type, etc. โ€” you permanently break the built-in within that scope.


๐ŸŽฏ Parameterised vs Non-Parameterised Functions

# Non-parameterised โ€” takes no input, asks inside the function
def add():
    a = int(input('Enter a number: '))
    b = int(input('Enter the next number: '))
    c = a + b
    print(c)

# Parameterised โ€” takes input directly via parameters
def add1(x, y):
    c = x + y
    print(c)

add1(18, 46)     # 18 and 46 are ARGUMENTS passed to PARAMETERS x and y

Parameter vs Argument โ€” exact definition:

Term Where it appears Example
Parameter In the function definition def add1(x, y): โ†’ x, y
Argument In the function call add1(18, 46) โ†’ 18, 46
def even_odd(x):
    if x % 2 == 0:
        print('Even')
    else:
        print('odd')

even_odd(37)        # 'odd'


โ˜๏ธ DevOps-Flavoured Function Examples

def restart_service(service_name):
    print(f"Restarting {service_name} service......")
    print(f"{service_name} restarted successfully")

restart_service("nginx")
restart_service("Docker")

def check_disk_usage():
    print("Checking disk usage...")
    print("Disk usage is 75%")

# Real system command execution
import os
def check_disk():
    os.system("df -h")        # runs actual shell command

lists have .append() but strings do NOT โ€” str1.append('xyz') โ†’ AttributeError. Strings are immutable, so there's no in-place method to add to them; use concatenation or += instead.


๐Ÿ”’ Part 2 โ€” Local vs Global Variables

Local Variables

def add(a, b):           # a, b, c are LOCAL โ€” only exist inside this function
    c = a + b
    print(c)

print(a)        # โŒ NameError: name 'a' is not defined โ€” 'a' doesn't exist outside the function
print(c)        # โŒ NameError โ€” same reason

Global Variables

x = 47          # global variable
y = 48          # global variable

def add1(x, y):       # these x, y are LOCAL parameters โ€” shadow the global ones
    c = x + y
    print(c)

add1(x, y)             # add1(47, 48) โ†’ prints 95
print(x)               # 47 โ€” global x is untouched, local x inside function was separate

Key rule: A local variable and a global variable can share the same name โ€” they are still two completely different variables. The function's local one "shadows" the global one only inside the function body.

Reading a Global Variable Inside a Function โ€” Works Fine

count = 10
def update1():
    global count
    print("Inside function:", count)   # can READ global without 'global' keyword too

update1()         # Inside function: 10

Modifying a Global Variable Without global โ€” Creates a NEW Local Variable

count = 10
def update():
    count = 20                          # this creates a NEW local 'count'
    print("Inside function:", count)    # Inside function: 20

update()
print(count)        # 10 โ€” the GLOBAL count is untouched!

The global Keyword โ€” Actually Modify the Global Variable

count = 10
def update2():
    global count          # tells Python: use the OUTER 'count', don't create a local one
    count = 20
    print("Inside function:", count)

update2()
print(count)        # 20 โ€” global count WAS modified this time

The #1 confusion point in this topic:

Code Effect on global variable
count = 20 (no global) inside function Creates a separate LOCAL variable โ€” global untouched
global count then count = 20 Modifies the actual GLOBAL variable

โ†ฉ๏ธ Part 3 โ€” return Statement

Print vs Return โ€” The Critical Difference

def add1(x, y):
    c = x + y
    return c              # sends value BACK to the caller

result1 = add1(10, 20)    # result1 now HOLDS the value 30
print(result1)             # 30
print(result1 ** 2)        # 900 โœ… โ€” can use the result further

def add2(x, y):
    c = x + y
    print(c)               # just prints โ€” doesn't send value back

result2 = add2(10, 20)     # prints 30, but returns nothing
print(result2)              # None  โš ๏ธ โ€” function with no return gives None
print(result2 ** 2)         # โŒ TypeError: unsupported operand for None

Golden Rule: Use print() inside a function only for display. Use return when you need to use the result later in your program (further calculations, conditions, storing in variables/lists).

return Terminates the Function Immediately

def add1(x, y):
    c = x + y
    return c
    print('Hello')        # โš ๏ธ NEVER runs โ€” return already exited the function

def add2(x, y):
    c = x + y
    print('Hello')        # runs FIRST โ€” this line is before return
    return c

add2(10, 20)               # prints 'Hello', then returns c (silently, unless captured)

Returning Multiple Values (as a Tuple)

def calc(x, y):
    c = x + y
    d = x - y
    return c, d            # returns BOTH โ€” Python packs them into a tuple

t = calc(20, 10)
print(t, type(t))          # (30, 10) <class 'tuple'>

Practical Functions โ€” Factorial & Prime Check

# Factorial
def factorial(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f

x = factorial(5)
print(x)            # 120

# Prime check
def is_prime():
    n = int(input('Enter a number: '))
    if n < 2:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    else:
        return True

print(is_prime())


๐Ÿ“ฅ Part 4 โ€” Types of Arguments

1. Positional argument
2. Keyword argument
3. Default argument
4. Variable-length argument
     a. *args    โ†’ variable positional args (tuple)
     b. **kwargs โ†’ variable keyword args (dict)

1. Positional Arguments โ€” Order Matters

def emp_details(name, age, salary):
    print('Name :- ', name)
    print('Age :- ', age)
    print('Salary :- ', salary)

emp_details('Sourav', 25, 75000)        # โœ… correct order
emp_details('Sourav', 75000, 25)        # โš ๏ธ runs but WRONG โ€” age=75000, salary=25 (logic bug!)
emp_details(25, 75000, 'Sourav')        # โš ๏ธ runs but completely scrambled

emp_details('Sourav', 75000)            # โŒ TypeError: missing required argument 'salary'

Rule: Number of arguments must exactly match number of parameters, and order determines which value goes to which parameter.

2. Keyword Arguments โ€” Name the Parameter Explicitly

emp_details('Sourav', 25, salary=75000)               # โœ… mix positional + keyword
emp_details('Sourav', age=25, salary=75000)            # โœ… all named after first
emp_details(salary=75000, age=25, name='Sourav')        # โœ… order doesn't matter when all keyworded

emp_details(salary=75000, age=25, Name='Sourav')        # โŒ TypeError โ€” 'Name' โ‰  'name' (case-sensitive!)
emp_details(salary=75000, age=25, 'Sourav')              # โŒ SyntaxError โ€” positional AFTER keyword not allowed

โš ๏ธ Critical Rule: If mixing positional and keyword arguments, all positional arguments must come BEFORE any keyword arguments.

3. Default Arguments โ€” Fallback Value if Not Provided

def emp_details(name, age, salary, loc='Bangalore'):    # loc has a default
    print('Name :- ', name)
    print('Age :- ', age)
    print('Salary :- ', salary)
    print('Location :- ', loc)

emp_details('Sourav', salary=75000, age=25)                          # loc defaults to 'Bangalore'
emp_details('Sourav', salary=75000, age=25, loc='Delhi')              # loc overridden to 'Delhi'

DevOps relevance: Default arguments are everywhere โ€” region='ap-south-1', timeout=30, retries=3 โ€” sensible defaults that can be overridden when needed.

4. Variable-Length Arguments

def add(x, y):
    return x + y

add(10, 38)              # โœ… works
add(37, 25, 58)           # โŒ TypeError โ€” too many arguments, only 2 parameters defined

*args โ€” Variable Positional Arguments โ†’ packed into a TUPLE

def xyz(*args):
    print(args, type(args))

xyz(10, 49, 28, 'Python')      # (10, 49, 28, 'Python') <class 'tuple'>

def add(*args):
    c = sum(args)
    return c

add(20, 49)                     # 69
add(18, 437, 28)                 # 483
add(37, 483, 746, 276, 373, 483, 27893)   # works with ANY number of arguments

`kwargs` โ€” Variable Keyword Arguments โ†’ packed into a DICT**

def abc(**kwargs):
    print(kwargs, type(kwargs))

abc(a=10, b=20, c=30, d=40)
# {'a': 10, 'b': 20, 'c': 30, 'd': 40} <class 'dict'>

DevOps relevance: *args/**kwargs are everywhere in real tools โ€” e.g., Boto3 functions, Django views, decorators โ€” to accept flexible config without hardcoding every possible parameter.


โšก Part 5 โ€” Lambda (Anonymous Functions)

# Syntax: lambda arguments: expression
# Called immediately: (lambda arguments: expression)(call_arguments)

# Add two numbers
(lambda x, y: x + y)(20, 48)        # 68

a = (lambda x, y: x * y)(20, 20)
print(a)                              # 400

# Conditional (ternary) inside lambda
(lambda a, b, c: a if a > b and a > c else b if b > a and b > c else c)(28, 37, 18)
# 37 โ€” finds the maximum of 3 numbers

(lambda x: 'Even' if x % 2 == 0 else 'Odd')(23)
# 'Odd'

When to use lambda: Quick, throwaway, single-expression functions โ€” especially as arguments to filter(), map(), reduce(), or sorted(key=...). NOT meant for complex multi-line logic (use a regular def for that).


๐Ÿ” Part 6 โ€” filter(), map(), reduce()

filter() โ€” Keep Elements That Match a Condition

# filter(lambda argument: condition, iterable)
# Returns a filter OBJECT โ€” wrap with list() or tuple() to see values

# Manual for-loop equivalent (what filter replaces):
lst = [1,2,3,4,5,6,7,8,9,10]
lst1 = []
for i in lst:
    if i % 2 == 0:
        lst1.append(i)
print(lst1)                          # [2,4,6,8,10]

# Same thing with filter() โ€” one line
print(list(filter(lambda x: x % 2 == 0, lst)))     # [2,4,6,8,10]

# DevOps example: flag high CPU usage servers
cpu_usage = [48, 27, 93, 14, 86]
high_cpu = list(filter(lambda x: x > 80, cpu_usage))
print(high_cpu)                       # [93, 86]

# Extract vowels from a string
str1 = 'ncihvewc cnoejife2oiyfecndlncjihuhew'
print(tuple(filter(lambda x: x.lower() in 'aeiou', str1)))

map() โ€” Apply an Operation to Every Element

# map(lambda argument: expression, iterable)
# Returns a map OBJECT โ€” wrap with list() or tuple()

# Manual for-loop equivalent:
lst = [1,2,3,4,5,6,7,8,9,10]
lst1 = []
for i in lst:
    lst1.append(i**2)
print(lst1)                           # [1,4,9,16,25,36,49,64,81,100]

# Same with map() โ€” one line
print(list(map(lambda x: x**2, lst)))   # [1,4,9,16,25,36,49,64,81,100]

# map() on heterogeneous list โ€” operation applies to EVERY element
lst = [1, 2, 3, 'Python', 4, 5, 6, 7, 'DevOps', 8, 9, 10]
print(list(map(lambda x: x*2, lst)))
# [2,4,6,'PythonPython',8,10,12,14,'DevOpsDevOps',16,18,20]
# Note: x*2 means NUMERIC doubling for numbers, STRING repetition for strings

# map() on a string โ€” applies to each character
str1 = "python"
print(list(map(lambda x: x*2, str1)))
# ['pp','yy','tt','hh','oo','nn']

filter() vs map() โ€” Core Difference:

Function Purpose Output size
filter() Keep only items matching a condition โ‰ค original (may shrink)
map() Transform every item = original (same size)

reduce() โ€” Aggregate to a Single Value

from functools import reduce      # must import โ€” not built-in like filter/map

# reduce(lambda x, y: expression, iterable)

lst = [1,2,3,4,5,6,7,8,9,10]
res = reduce(lambda x, y: x + y, lst)
print(res)                          # 55 โ€” sum of all elements

# Find minimum
reduce(lambda x, y: x if x < y else y, lst)    # 1

# Find maximum
reduce(lambda x, y: x if x > y else y, lst)    # 10

How reduce() works internally: It takes the first two elements, applies the lambda, takes that result + the next element, applies the lambda again โ€” repeating until one value remains.


๐Ÿ“ฆ Part 7 โ€” Modules

# A module = a .py file containing functions/classes
# Access with: module_name.function_name()

import Mod                  # imports Mod.py
Mod.greet()                  # calls greet() function inside Mod.py
Mod.adding(37, 27)
Mod.mul(37, 17)

Best practice: Don't put "free executable code" (code that runs immediately on import) inside a module โ€” only function/class definitions. This keeps the module reusable and side-effect-free when imported elsewhere.

DevOps relevance: This is exactly how you'd structure a utils.py or aws_helpers.py module with reusable functions like get_ec2_status(), restart_service(), parse_log() โ€” imported across multiple automation scripts.


โ˜๏ธ DevOps / Cloud Use Cases

# 1. Reusable service restart function with default region
def restart_service(service_name, region='ap-south-1'):
    print(f"Restarting {service_name} in {region}...")

restart_service('nginx')
restart_service('nginx', region='us-east-1')

# 2. *args to accept any number of servers to health-check
def health_check(*servers):
    for s in servers:
        print(f'Checking {s}...')

health_check('web-01', 'web-02', 'db-01')

# 3. **kwargs to accept flexible AWS-style config
def launch_instance(**config):
    print(config)

launch_instance(instance_type='t2.micro', region='ap-south-1', count=2)

# 4. filter() to find unhealthy servers
server_status = {'web-01': 200, 'web-02': 500, 'db-01': 200, 'cache-01': 503}
unhealthy = list(filter(lambda s: server_status[s] != 200, server_status))
print(unhealthy)                      # ['web-02', 'cache-01']

# 5. map() to convert a list of instance IDs into ARNs
instance_ids = ['i-001', 'i-002', 'i-003']
arns = list(map(lambda i: f'arn:aws:ec2:ap-south-1:123456789:instance/{i}', instance_ids))
print(arns)

# 6. reduce() to sum total monthly AWS costs across services
from functools import reduce
service_costs = [120.50, 45.25, 300.10, 15.00]
total = reduce(lambda x, y: x + y, service_costs)
print(f'Total monthly cost: ${total}')

# 7. global + counter pattern for tracking retries across calls
retry_count = 0
def attempt_connection():
    global retry_count
    retry_count += 1
    print(f'Attempt #{retry_count}')

attempt_connection()
attempt_connection()
print(f'Total retries: {retry_count}')


โŒ Common Mistakes

Mistake Code Fix
Confusing print() and return Function uses print(), then tries result = func() and uses result Use return when you need the value later
Forgetting global keyword count = 20 inside function โ€” global stays unchanged Use global count before modifying
Code after return Lines after return never execute Put cleanup/logging BEFORE return
Positional after keyword f(a=1, 2) All positional args must come first
Case-sensitive keyword names f(Name='x') when param is name Match exact parameter name and case
Shadowing built-ins with function names def len(): ... Never name functions after built-ins
Forgetting list()/tuple() around filter/map print(filter(...)) โ†’ shows object, not values Wrap with list() or tuple()
Forgetting to import functools for reduce reduce(...) โ†’ NameError from functools import reduce
String .append() str1.append('x') Strings are immutable โ€” use += or concatenation

๐ŸŽฏ Interview Points

  1. "Difference between parameter and argument?"
    โ†’ Parameter is the variable name in the function definition. Argument is the actual value passed when calling the function.

  2. "Difference between local and global variables?"
    โ†’ Local variables exist only inside the function where they're defined. Global variables are defined outside any function and accessible everywhere โ€” but a function can't modify a global variable without the global keyword.

  3. "What does the global keyword do?"
    โ†’ It tells Python that an assignment inside a function should modify the OUTER (global) variable instead of creating a new local one.

  4. "Difference between print() and return inside a function?"
    โ†’ print() just displays output to console โ€” the function still returns None. return sends the value back to the caller so it can be stored or reused.

  5. "What happens to code written after a return statement?"
    โ†’ It never executes โ€” return immediately exits the function.

  6. "Difference between *args and `kwargs?"**
    โ†’
    args collects extra positional arguments into a tuple. *kwargs` collects extra keyword arguments into a dictionary.

  7. "Difference between filter() and map()?"
    โ†’ filter() returns only the elements that satisfy a condition (output may be smaller). map() applies a transformation to every element (output is always the same size).

  8. "Why do you need to import reduce but not filter/map?"
    โ†’ filter() and map() are built-in functions. reduce() lives in the functools module and must be explicitly imported.

  9. "What is a lambda function and when would you use it?"
    โ†’ An anonymous, single-expression function โ€” used for short, throwaway logic, typically as an argument to filter(), map(), reduce(), or sorted().

  10. "Can a function return multiple values?"
    โ†’ Yes โ€” Python packs them into a tuple automatically: return c, d โ†’ caller receives (c, d).


๐Ÿ“š Knowledge Base โ€” Quick Revision

# โ”€โ”€ FUNCTION BASICS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def func_name(param1, param2):     # definition
    ...
    return value                    # optional

func_name(arg1, arg2)               # call โ€” this is what executes it

# โ”€โ”€ SCOPE โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
x = 10                  # global
def f():
    x = 20               # LOCAL โ€” does NOT affect global x
def g():
    global x
    x = 20               # modifies the actual global x

# โ”€โ”€ ARGUMENT TYPES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def f(a, b):              pass    # positional
f(a=1, b=2)                       # keyword
def f(a, b=10):            pass   # default (b optional)
def f(*args):               pass  # variable positional โ†’ tuple
def f(**kwargs):             pass # variable keyword โ†’ dict

# Rule: positional args must come BEFORE keyword args in a call

# โ”€โ”€ RETURN VS PRINT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def f():
    return 5      # value usable later: x = f()
def g():
    print(5)       # just displays; g() itself returns None

# โ”€โ”€ LAMBDA โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
lambda x, y: x + y                              # basic
lambda x: 'Even' if x % 2 == 0 else 'Odd'        # ternary inside lambda

# โ”€โ”€ FILTER / MAP / REDUCE โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
list(filter(lambda x: condition, iterable))      # keep matching items
list(map(lambda x: expression, iterable))        # transform every item
from functools import reduce
reduce(lambda x, y: expression, iterable)        # aggregate to ONE value

# โ”€โ”€ MODULES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
import module_name
module_name.function_name()


๐Ÿ‹๏ธ Practice Questions

Easy

  1. Write a function square(n) that takes a number and returns its square. Call it and print the result.
  2. Write a function greet(name, greeting='Hello') with a default argument. Call it once with just a name, and once overriding the greeting.
  3. Use lambda to write a one-line function that checks if a number is positive, negative, or zero.

Medium

  1. Write a function total(*args) that accepts any number of numbers and returns their sum using reduce().
  2. Demonstrate the difference between local and global scope: create a global variable counter = 0, write a function that tries to increment it without global, show it fails to update, then fix it using the global keyword.
  3. Given cpu_list = [45, 78, 92, 33, 88, 67], use filter() to get servers with CPU > 70, and map() to convert all values to strings with a % symbol (e.g., '45%').

DevOps-Focused

  1. Service Manager Function: Write a function manage_service(action, service_name, region='ap-south-1') that prints a message like "Performing 'restart' on nginx in ap-south-1". Call it 3 times: once with all positional args, once with keyword args in different order, and once overriding the region.
  2. Cost Calculator with reduce(): Given a list of dicts representing AWS services and their monthly costs:
   services = [
       {'name': 'EC2', 'cost': 120.50},
       {'name': 'S3', 'cost': 45.25},
       {'name': 'RDS', 'cost': 300.10},
   ]

Use map() to extract just the costs into a list, then use reduce() (with functools) to calculate the total. Print: "Total AWS monthly cost: $465.85".