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

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

Application and Cybersecurity Blog
Application and Cybersecurity Blog
A
About on SuperTechFans
S
SegmentFault ๆœ€ๆ–ฐ็š„้—ฎ้ข˜
ๅฅ‡ๅฎขSolidotโ€“ไผ ้€’ๆœ€ๆ–ฐ็ง‘ๆŠ€ๆƒ…ๆŠฅ
ๅฅ‡ๅฎขSolidotโ€“ไผ ้€’ๆœ€ๆ–ฐ็ง‘ๆŠ€ๆƒ…ๆŠฅ
Help Net Security
Help Net Security
ๆœ‰่ตžๆŠ€ๆœฏๅ›ข้˜Ÿ
ๆœ‰่ตžๆŠ€ๆœฏๅ›ข้˜Ÿ
ๅš
ๅšๅฎขๅ›ญ - ใ€ๅฝ“่€็‰นใ€‘
O
OpenAI News
็พŽ
็พŽๅ›ขๆŠ€ๆœฏๅ›ข้˜Ÿ
ๆœˆๅ…‰ๅšๅฎข
ๆœˆๅ…‰ๅšๅฎข
Apple Machine Learning Research
Apple Machine Learning Research
Schneier on Security
Schneier on Security
Webroot Blog
Webroot Blog
Cyberwarzone
Cyberwarzone
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google Online Security Blog
Google Online Security Blog
T
Tenable Blog
S
Security Affairs
ๅš
ๅšๅฎขๅ›ญ_้ฆ–้กต
S
Schneier on Security
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
T
Tailwind CSS Blog
ๅคง็Œซ็š„ๆ— ้™ๆธธๆˆ
ๅคง็Œซ็š„ๆ— ้™ๆธธๆˆ
Spread Privacy
Spread Privacy
้‡
้‡ๅญไฝ
่ฎฉๅฐไบงๅ“็š„็‹ฌ็ซ‹ๅ˜็Žฐๆ›ด็ฎ€ๅ• - ezindie.com
่ฎฉๅฐไบงๅ“็š„็‹ฌ็ซ‹ๅ˜็Žฐๆ›ด็ฎ€ๅ• - ezindie.com
K
Kaspersky official blog
Hugging Face - Blog
Hugging Face - Blog
TaoSecurity Blog
TaoSecurity Blog
ๅš
ๅšๅฎขๅ›ญ - ่‚ๅพฎไธœ
Vercel News
Vercel News
M
MIT News - Artificial intelligence
T
Troy Hunt's Blog
B
Blog
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
Attack and Defense Labs
Attack and Defense Labs
L
LINUX DO - ๆœ€ๆ–ฐ่ฏ้ข˜
D
DataBreaches.Net
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
ๅš
ๅšๅฎขๅ›ญ - Franky
W
WeLiveSecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Check Point Blog
H
Hacker News: Front Page

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
while Loop, break & continue, Lists (Creation, Mutability, Methods, List Comprehension)
Tejas Shinkar ยท 2026-06-20 ยท via DEV Community

๐Ÿ“Œ Key Concepts Overview

Concept One-Line Definition
while loop Repeats code as long as a condition is True
while True Infinite loop โ€” needs break to stop
break Immediately exits the loop
continue Skips current iteration, moves to next
List Ordered, mutable collection โ€” heterogeneous elements allowed
List Comprehension One-line way to build a list using a loop + condition
List Mutability Lists can be changed in place โ€” id() stays the same

๐Ÿ” Part 1 โ€” while Loop

The 3 Components (Critical Pattern)

# 1. Initialisation  2. Condition  3. Increment/Decrement

a = 1                  # 1. Initialisation
while a <= 10:          # 2. Condition
    print('Devops')
    a += 1              # 3. Increment

# Without increment โ†’ INFINITE LOOP (condition never becomes False)

How it works: Condition is checked before each iteration. As soon as it's False, the loop stops. Miss the increment/decrement โ†’ infinite loop (a real production hazard โ€” can hang a script or burn CPU).

while โ€” Practical Patterns

# Countdown (decrement)
a = 10
while a > 0:
    print('Devops')
    a -= 1

# Sum of 1 to 20
total = 0
a = 1
while a <= 20:
    total += a
    a += 1
print(total)        # 210

# Product (factorial-style) of 1 to 20
product = 1
a = 1
while a <= 20:
    product *= a
    a += 1
print(product)

# Pattern using while + string repetition
str1 = 'Devops'
i = 0
while i < len(str1):
    print(str1[i] * (i + 1))
    i += 1
# D
# ee
# vvv
# oooo
# ppppp
# ssssss

for vs while โ€” When to Use Which

Use for Use while
You know the iterable / number of repetitions You don't know how many times โ€” depends on a condition
Looping over list, string, range Retry logic, polling, waiting for a state
# DevOps: retry logic โ€” classic while True use case
max_attempts = 5
attempt = 0
while attempt < max_attempts:
    print(f'Attempt {attempt+1}: Connecting to server...')
    # if connection succeeds: break
    attempt += 1

while True โ€” Infinite Loop Pattern

# Always True โ€” runs forever until break is hit
# Used for: retry logic, polling, menu-driven scripts, password validation

password = 'xyz1234'
p = input('Enter your password: ')
while True:
    if p == password:
        print('Password matched')
        break                          # exits the loop
    else:
        print('Incorrect password. Try again')
        p = input('Enter your password: ')

DevOps real use: polling an AWS resource until it reaches running state, retrying an API call until success, watching a deployment status.

# Simulated polling pattern (real-world shape)
status = 'pending'
checks = 0
while True:
    checks += 1
    print(f'Check #{checks}: status = {status}')
    if status == 'running':
        print('โœ… Instance is up')
        break
    if checks >= 5:
        print('โŒ Timeout waiting for instance')
        break
    # status = check_instance_status()   # in real code
    status = 'running' if checks == 3 else 'pending'   # simulate


โญ๏ธ Part 2 โ€” Transfer Statements: break & continue

break โ€” Exit the Loop Entirely

lst = [1, 37, 'Python', True, None, 'Devops', 38, 483, 38.438]

# Print elements until None is found, then stop
for i in lst:
    if i == None:
        break
    else:
        print(i)
# Output: 1, 37, Python, True   (stops at None)

continue โ€” Skip Current Iteration Only

lst = [1, 37, None, 'Python', True, None, 'Devops', 38, 483, None, 38.438]

# Skip None values, but KEEP looping through the rest
for i in lst:
    if i == None:
        continue          # skip this iteration, move to next
    else:
        print(i)
# Output: 1, 37, Python, True, Devops, 38, 483, 38.438   (all non-None values)

The Key Difference:

Statement Effect Loop continues?
break Stops the loop completely โŒ No โ€” exits
continue Skips just this one iteration โœ… Yes โ€” moves to next

break in Nested Loops โ€” Only Breaks the Inner Loop

lst = ['peter', 'piper', 'picked']

# break in inner loop only โ€” outer loop continues
for word in lst:
    for char in word:
        print(char)
        break              # breaks INNER loop only โ€” prints first char of each word
# p, p, p   (first letter of each word)

# break in outer loop โ€” stops everything after first word
for word in lst:
    for char in word:
        print(char)
    break                  # breaks OUTER loop โ€” only processes 'peter'
# p, e, t, e, r

# break in both โ€” exits after just ONE character total
for word in lst:
    for char in word:
        print(char)
        break
    break
# p   (only)

โš ๏ธ Critical for interviews: break/continue only affects the loop they're directly inside โ€” not outer loops.


๐Ÿ“ฆ Part 3 โ€” Lists Deep Dive

List Basics

# Heterogeneous โ€” any mix of types allowed
lst = [1, 37, None, 'Python', True, None, 'Devops', 38, 483, None, 38.438]
print(lst, type(lst))

List Operations

# Concatenation โ€” combine two lists
lst = [1, 2, 3, 4, 5]
lst1 = [6, 7, 8, 9, 10]
print(lst + lst1)             # [1,2,3,4,5,6,7,8,9,10]

# โš ๏ธ + does NOT modify in place โ€” must reassign
lst + [50]
print(lst)                    # unchanged! still [1,2,3,4,5]
lst = lst + [50]              # โœ… now it's updated

# โŒ Can't add a list and a non-iterable directly
# lst + 50   โ†’ TypeError: can only concatenate list (not "int") to list

# Repetition
lst = [1, 2, 3, 4, 5]
print(lst * 5)                # repeats the whole list 5 times

# Length
print(len(lst))                # 5

# Indexing
print(lst[2])                  # 3rd element (0-indexed)

# Slicing
print(lst[::1])                 # full copy, same order
print(lst[::-1])                # reversed list

Nested Lists & Deep Indexing

lst = [37, 'Python', 23+37j, True, [1, 36, 'Devops'],
       [['Linux', 'AWS', 'Learnbay'], 73, 73.476, 51, 'Hello'],
       'Sunday', 'weekend',
       ['Hello', ['hey', 'WFH', [37, 26.437, False], 'Functions']]]

print(lst[5][4])      # 'Hello' โ€” index 5 โ†’ that sub-list โ†’ index 4
print(lst[8][1][2][1])  # drilling 4 levels deep

# DevOps relevance: nested JSON/API responses look exactly like this
# e.g., ec2_response['Reservations'][0]['Instances'][0]['State']['Name']

Mutability โ€” The Core List Property

lst = [1, 2, 3, 4, 5]
print(id(lst))           # e.g. 140234...

lst[2] = 'Python'        # modify in place โ€” item assignment
print(lst)               # [1, 2, 'Python', 4, 5]
print(id(lst))           # SAME id โ€” list was modified, not recreated

Why this matters: Lists are mutable โ€” changing them doesn't create a new object. This is different from strings/tuples (immutable), where any "change" actually creates a brand-new object.


๐Ÿ—๏ธ Ways to Create a List

# Case 1 โ€” Direct literal (when you know elements)
lst = [1, 2, 34, 5, 6, 'python', True]

# Case 2 โ€” Using list() on an iterable
list('Python')              # ['P','y','t','h','o','n']
list((10, 20, 30, 40))      # from a tuple โ†’ [10,20,30,40]
list(range(12, 24))         # from a range โ†’ [12,13,...,23]
list(input('Enter: '))      # from input string โ†’ char by char list

# โš ๏ธ list() on a single non-iterable-wrapped value vs a list with one item
list(['Python'])            # ['Python']  โ€” already a list with 1 string
list('Python')              # ['P','y','t','h','o','n']  โ€” string exploded char by char

# Case 3 โ€” List Comprehension (most DevOps-relevant!)
# Syntax: [expression for item in iterable if condition]

lst = [i for i in range(1, 11)]                     # [1,2,...,10]
lst = [i**2 for i in range(1, 21) if i % 2 == 0]    # squares of even numbers 1-20

# Compare to the manual for-loop equivalent:
lst = []
for i in range(1, 11):
    lst += [i]
# vs the one-liner:
lst = [i for i in range(1, 11)]


๐Ÿ› ๏ธ List Methods โ€” Full Reference

dir(lst)    # shows all available methods on a list object

append() โ€” Add ONE Item to the End

lst = [1, 2, 3, 4, 5]
lst.append(30)              # [1,2,3,4,5,30]
lst.append([30, 50])        # adds the WHOLE list as ONE nested item
                             # [1,2,3,4,5,30,[30,50]]  โš ๏ธ not flattened!
lst.append('Python')        # adds as a single string element

# โŒ append() only takes ONE argument
# lst.append(30, 50)   โ†’ TypeError

extend() โ€” Add Items One-by-One (Flatten an Iterable In)

lst = [100, 200, 300, 400, 500]
lst.extend('Python')        # adds each CHARACTER separately
print(lst)                  # [100,200,300,400,500,'P','y','t','h','o','n']

lst = [1, 2, 3, 4, 5]
lst.extend([30, 50])        # adds each element separately
print(lst)                  # [1,2,3,4,5,30,50]

append() vs extend() โ€” THE classic interview question:

Method Adds Example
append(x) x as a single element (even if x is a list) lst.append([1,2]) โ†’ [...,[1,2]]
extend(x) each element of x individually lst.extend([1,2]) โ†’ [...,1,2]

insert() โ€” Insert at a Specific Index

# lst.insert(index, value)
lst = [1, 37, None, 'Python', True]
lst.insert(2, 'Sunday')      # inserts BEFORE index 2, shifts rest right
print(lst)                   # [1, 37, 'Sunday', None, 'Python', True]

lst.insert(-2, 'Python')     # works with negative indexing too

count() โ€” Count Occurrences

lst = [1, 2, 3, 1, 2, 3, 1, 2, 3]
print(lst.count(2))          # 3
print(lst.count(1))          # 3

index() โ€” Find Position of First Occurrence

lst = [1, 2, 3, 1, 2, 3]
print(lst.index(2))          # 1 (first occurrence, left to right)
print(lst.index(20))         # โŒ ValueError: 20 is not in list

pop() โ€” Remove by Index (Returns the Removed Value)

# lst.pop(index)  โ€” default removes the LAST item
lst = [100, 200, 300, 400, 500]
removed = lst.pop(2)          # removes index 2 โ†’ returns 300
print(removed)                # 300
print(lst)                    # [100,200,400,500]

lst.pop()                     # removes LAST item by default
lst.pop(-2)                   # negative indexing works too

# โŒ Invalid index โ†’ IndexError: pop index out of range

remove() โ€” Remove by VALUE (Not Index)

# lst.remove(value) โ€” removes FIRST occurrence, returns nothing
lst = [100, 200, 300, 400, 300, 500]
lst.remove(300)               # removes the FIRST 300 only
print(lst)                    # [100,200,400,300,500]

# โŒ Value not in list โ†’ ValueError

pop() vs remove() โ€” Interview Favourite:

Method Removes by Returns Error if missing
pop(index) position/index the removed value IndexError
remove(value) the value itself None ValueError

reverse() โ€” Reverses In Place

lst = [1, 2, 3, 4, 5]
lst.reverse()
print(lst)        # [5,4,3,2,1] โ€” modifies original list

sort() โ€” Sorts In Place (Ascending by Default)

lst = [72, 48, 216, 4873, 462, 9]
lst.sort()                    # ascending
lst.sort(reverse=True)        # descending

# Works on strings too (alphabetical / ASCII order)
lst = list('coiuhihcbciygdhs')
lst.sort()

# โš ๏ธ sort() FAILS on mixed/heterogeneous types
lst = [1, 'Python', True, 38.438]
# lst.sort()   โ†’ TypeError: can't compare str and int

clear() โ€” Empty the List (Same Object, Same id())

lst = [1, 37, 'Python', True]
print(id(lst))
lst.clear()
print(lst)            # []
print(id(lst))        # SAME id โ€” emptied in place, not a new object

copy() โ€” Create an Independent Copy (CRITICAL CONCEPT)

# โŒ WITHOUT copy() โ€” both variables point to the SAME list (same id)
lst = [1, 2, 3, 4, 5]
lst1 = lst                    # NOT a copy โ€” just another name for the same object
lst1[2] = 93
print(lst1)                   # [1,2,93,4,5]
print(lst)                    # [1,2,93,4,5]  โš ๏ธ original also changed!

# โœ… WITH copy() โ€” independent list, different id
lst = [1, 2, 3, 4, 5]
lst1 = lst.copy()             # new object, different id
lst1[2] = 93
print(lst1)                   # [1,2,93,4,5]
print(lst)                    # [1,2,3,4,5]  โœ… original untouched

This is one of the most important bugs to understand in Python. lst1 = lst does NOT copy โ€” it just creates a second reference to the exact same list in memory.

Manual String Split (Building Towards .split())

# Class built this manually to understand the LOGIC behind str.split()
str1 = 'Peter piper picked a pack of pickeled peppers'

lst = []
res = ''
for char in str1:
    if char != ' ':
        res += char
    else:
        lst.append(res)
        res = ''
lst.append(res)          # don't forget the last word!
print(lst)
# ['Peter', 'piper', 'picked', 'a', 'pack', 'of', 'pickeled', 'peppers']

# This is literally what str.split() does internally:
print(str1.split())      # same result, one line


โ˜๏ธ DevOps / Cloud Use Cases

# 1. Poll AWS instance status until running (while True pattern)
status = 'pending'
attempts = 0
while True:
    attempts += 1
    if status == 'running':
        print('โœ… Instance ready')
        break
    if attempts > 10:
        print('โŒ Timeout โ€” instance not ready')
        break
    # status = get_instance_status()   # real AWS SDK call

# 2. Retry failed deployment with break on success
max_retries = 3
attempt = 0
while attempt < max_retries:
    attempt += 1
    print(f'Deploy attempt {attempt}...')
    success = (attempt == 2)        # simulated
    if success:
        print('โœ… Deployed')
        break
else:
    print('โŒ All retries failed')

# 3. Filter out failed health checks using continue
servers_status = ['ok', 'fail', 'ok', None, 'ok', 'fail']
for status in servers_status:
    if status is None or status == 'fail':
        continue
    print(f'โœ… Server status: {status}')

# 4. Build list of running instance IDs with list comprehension
instances = [
    {'id': 'i-001', 'state': 'running'},
    {'id': 'i-002', 'state': 'stopped'},
    {'id': 'i-003', 'state': 'running'},
]
running_ids = [inst['id'] for inst in instances if inst['state'] == 'running']
print(running_ids)        # ['i-001', 'i-003']

# 5. extend() to merge server lists from multiple regions
us_servers = ['web-us-1', 'web-us-2']
eu_servers = ['web-eu-1', 'web-eu-2']
all_servers = []
all_servers.extend(us_servers)
all_servers.extend(eu_servers)
print(all_servers)

# 6. copy() before modifying a shared config list
base_ports = [22, 80, 443]
web_ports = base_ports.copy()
web_ports.append(8080)
print(base_ports)         # unaffected โ€” still [22, 80, 443]
print(web_ports)          # [22, 80, 443, 8080]


โŒ Common Mistakes

Mistake Code Fix
Forgetting increment in while while a<=10: print(a) (no a+=1) Infinite loop โ€” always increment/decrement
lst + [x] doesn't modify list lst + [50] then expects lst changed Reassign: lst = lst + [50]
append() vs extend() confusion lst.append([1,2]) โ†’ adds nested list, not 2 items Use extend() to flatten in
lst1 = lst thinking it's a copy Modifying lst1 also changes lst Use lst1 = lst.copy()
sort() on mixed types [1,'a',True].sort() TypeError โ€” sort only same-type lists
pop() on empty/invalid index [].pop() IndexError โ€” check length first
remove() on missing value lst.remove(999) when not present ValueError โ€” check in first
break only exits ONE loop level Expecting break to exit nested loops fully Need a flag or function return for full exit

๐ŸŽฏ Interview Points

  1. "Difference between append() and extend()?"
    โ†’ append() adds its argument as a single element (even a whole list becomes one nested item). extend() iterates through its argument and adds each element individually.

  2. "Difference between break and continue?"
    โ†’ break exits the loop entirely. continue skips only the current iteration and proceeds to the next one.

  3. "Difference between pop() and remove()?"
    โ†’ pop(index) removes by position and returns the value; default removes the last item. remove(value) removes the first matching value and returns nothing.

  4. "What happens when you do lst1 = lst vs lst1 = lst.copy()?"
    โ†’ lst1 = lst makes lst1 point to the SAME object โ€” changes to one affect the other. .copy() creates an independent object with a new id().

  5. "Why are lists mutable?"
    โ†’ Their contents can be changed after creation (id() stays the same) โ€” unlike strings/tuples where any change creates a new object.

  6. "What's a list comprehension and why use it?"
    โ†’ A concise one-line way to build a list: [expr for item in iterable if condition]. More Pythonic and often faster than a manual for-loop + append.

  7. "When would you use while True over a regular while?"
    โ†’ When the exit condition is checked INSIDE the loop body rather than at the top โ€” e.g., retry logic, polling, "ask again until valid input."


๐Ÿ“š Knowledge Base โ€” Quick Revision

# โ”€โ”€ WHILE LOOP โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
a = 1                       # 1. init
while a <= 10:               # 2. condition
    ...
    a += 1                    # 3. increment โ€” NEVER forget this

while True:                  # infinite โ€” needs break
    if condition:
        break

# โ”€โ”€ BREAK / CONTINUE โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
break        # exits the loop entirely
continue     # skips current iteration, loop continues

# โ”€โ”€ LIST CREATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
lst = [1, 2, 3]                       # literal
lst = list('abc')                     # from string โ†’ ['a','b','c']
lst = list(range(5))                  # from range
lst = [i for i in range(10)]          # comprehension
lst = [i**2 for i in range(10) if i%2==0]   # comprehension + filter

# โ”€โ”€ LIST OPERATIONS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
lst + lst2          # concatenation (new list, must reassign)
lst * 3              # repetition
len(lst)              # length
lst[i]                # indexing
lst[::-1]             # reverse via slicing

# โ”€โ”€ LIST METHODS (mutating, in-place) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
lst.append(x)         # add ONE item to end
lst.extend(iterable)  # add items individually
lst.insert(i, x)      # insert before index i
lst.pop(i)            # remove by index, RETURNS value (default: last)
lst.remove(x)         # remove by VALUE, first match, returns None
lst.reverse()         # reverse in place
lst.sort()            # ascending; sort(reverse=True) for descending
lst.clear()           # empty the list (same id)
lst.count(x)          # occurrences of x
lst.index(x)          # first index of x (ValueError if missing)
lst.copy()            # independent shallow copy (new id)

# โ”€โ”€ CRITICAL GOTCHA โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
lst1 = lst             # โŒ same object โ€” NOT a copy
lst1 = lst.copy()      # โœ… independent copy


๐Ÿ‹๏ธ Practice Questions

Easy

  1. Write a while loop that prints numbers from 10 down to 1.
  2. Given lst = [10, 20, 30, 40, 50], use append() to add 60, then extend() to add [70, 80]. Print the list after each step.
  3. Use a list comprehension to create a list of cubes (xยณ) for numbers 1 to 10.

Medium

  1. Write a while True loop that keeps asking the user to enter a number until they enter a number greater than 100, then breaks and prints "Valid number entered."
  2. Given lst = [5, 10, None, 15, None, 20], write a loop using continue to print only non-None values, and a separate loop using break to print values until the first None.
  3. Demonstrate the lst1 = lst vs lst1 = lst.copy() bug with code: create a list, assign it without .copy(), modify the copy, and show the original also changed. Then fix it using .copy().

DevOps-Focused

  1. Retry Connector: Write a while loop that simulates connecting to a server. It should try up to 5 times. Use a variable connected = False that becomes True on the 3rd attempt (simulated). Print each attempt, and break with a success message once connected, or a failure message after 5 failed attempts.
  2. Server List Builder: You have two lists: prod_servers = ['web-01','web-02'] and staging_servers = ['stg-01','stg-02']. Use extend() to build one combined all_servers list. Then use a list comprehension to create prod_only containing only servers that start with 'web'. Print both results.