{"id":1169,"date":"2026-10-17T21:05:01","date_gmt":"2026-10-17T15:35:01","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=1169"},"modified":"2026-10-17T21:07:50","modified_gmt":"2026-10-17T15:37:50","slug":"python-interview-questions","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/python-interview-questions\/","title":{"rendered":"100 Python Interview Questions and Answers for Freshers and Experienced (Free PDF)"},"content":{"rendered":"\n<style>.cdai{--cd-brand:#3c3fde;--cd-brand-soft:#eceeff;--cd-ink:#14162b;--cd-muted:#5b5f7a;--cd-line:#dfe1ee;--cd-card:#ffffff;--cd-bg:#f6f7fc;--cd-good:#0f8a5f;--cd-good-soft:#e3f6ee;--cd-bad:#c2410c;--cd-bad-soft:#fdebe1;--cd-warn:#b7791f;--cd-on-brand:#ffffff;\nfont-family:Inter,system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;color:var(--cd-ink);background:var(--cd-bg);border:1px solid var(--cd-line);border-radius:14px;padding:22px;margin:28px 0;line-height:1.55;font-size:16px;box-sizing:border-box;max-width:100%;overflow:hidden}\n.s-dark .cdai,.cdai.cd-dark{--cd-brand:#8d90ff;--cd-brand-soft:#23254a;--cd-ink:#e8e9f5;--cd-muted:#a3a6c2;--cd-line:#32354f;--cd-card:#1b1d33;--cd-bg:#14162a;--cd-good:#4ccf98;--cd-good-soft:#163a2c;--cd-bad:#ff9a6b;--cd-bad-soft:#3d2316;--cd-warn:#f2c46b;--cd-on-brand:#0f1030}\n.cdai *,.cdai *::before,.cdai *::after{box-sizing:border-box}\n.cdai h4.cd-h{font-family:Outfit,Inter,sans-serif;font-size:1.25rem;font-weight:700;margin:0 0 4px;color:var(--cd-ink);line-height:1.3}\n.cdai .cd-sub{color:var(--cd-muted);font-size:.95rem;margin:0 0 16px}\n.cdai .cd-tag{display:inline-block;font-size:.72rem;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--cd-brand);background:var(--cd-brand-soft);padding:3px 9px;border-radius:99px;margin-bottom:10px}\n.cdai button.cd-btn,.cdai .cd-chip{font:inherit;font-size:.92rem;font-weight:600;cursor:pointer;border-radius:10px;border:1.5px solid var(--cd-line);background:var(--cd-card);color:var(--cd-ink);padding:9px 14px;line-height:1.3;transition:transform .15s ease,border-color .15s ease,background .15s ease;text-transform:none;letter-spacing:normal;box-shadow:none;margin:0;min-height:0;height:auto}\n.cdai button.cd-btn:hover,.cdai .cd-chip:hover{border-color:var(--cd-brand);transform:translateY(-1px)}\n.cdai button.cd-btn:focus-visible,.cdai .cd-chip:focus-visible,.cdai input:focus-visible{outline:3px solid var(--cd-brand);outline-offset:2px}\n.cdai .cd-primary,.cdai button.cd-primary{background:var(--cd-brand);border-color:var(--cd-brand);color:var(--cd-on-brand)}\n.cdai .cd-chip[aria-pressed=\"true\"]{background:var(--cd-brand);border-color:var(--cd-brand);color:var(--cd-on-brand)}\n.cdai .cd-row{display:flex;flex-wrap:wrap;gap:10px;align-items:center}\n.cdai .cd-grid2{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,230px),1fr));gap:12px}\n.cdai .cd-card{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:12px;padding:14px}\n.cdai .cd-stat{font-family:Outfit,Inter,sans-serif;font-size:2rem;font-weight:700;color:var(--cd-brand);line-height:1.1;font-variant-numeric:tabular-nums}\n.cdai .cd-small{font-size:.85rem;color:var(--cd-muted)}\n.cdai label.cd-lab{font-weight:600;font-size:.92rem;display:flex;justify-content:space-between;gap:10px;margin:14px 0 6px}\n.cdai input[type=range]{width:100%;accent-color:var(--cd-brand);margin:0;height:28px;background:transparent;border:0;padding:0}\n.cdai canvas{display:block;width:100%;height:auto;border-radius:10px;background:var(--cd-card);border:1px solid var(--cd-line);touch-action:pan-y}\n\/* hero *\/\n.cdai.cd-hero{padding:0;position:relative;background:#101233;border-color:#24275a}\n.cdai.cd-hero canvas{border:0;border-radius:0;background:transparent;height:200px}\n.cdai.cd-hero .cd-hero-txt{position:absolute;left:0;right:0;bottom:0;padding:16px 20px;background:linear-gradient(transparent,rgba(16,18,51,.92) 55%);color:#fff}\n.cdai.cd-hero .cd-hero-txt b{font-family:Outfit,Inter,sans-serif;font-size:1.15rem}\n.cdai.cd-hero .cd-hero-txt span{display:block;color:#c9cbff;font-size:.9rem}\n\/* planner *\/\n.cdai .cd-timeline{display:flex;flex-direction:column;gap:7px;margin-top:6px}\n.cdai .cd-tl-row{display:grid;grid-template-columns:minmax(0,150px) 1fr 62px;gap:10px;align-items:center;font-size:.88rem}\n.cdai .cd-tl-name{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.cdai .cd-tl-name a{color:inherit;text-decoration:none}\n.cdai .cd-tl-name a:hover{color:var(--cd-brand)}\n.cdai .cd-tl-track{height:14px;background:var(--cd-brand-soft);border-radius:99px;overflow:hidden}\n.cdai .cd-tl-bar{height:100%;background:var(--cd-brand);border-radius:99px;width:0;transition:width .6s cubic-bezier(.2,.8,.2,1)}\n.cdai .cd-tl-bar.cd-skim{background:repeating-linear-gradient(45deg,var(--cd-brand),var(--cd-brand) 6px,transparent 6px,transparent 10px)}\n.cdai .cd-tl-w{text-align:right;font-variant-numeric:tabular-nums;color:var(--cd-muted)}\n.cdai .cd-prog{height:10px;border-radius:99px;background:var(--cd-brand-soft);overflow:hidden;margin-top:8px}\n.cdai .cd-prog i{display:block;height:100%;background:var(--cd-good);width:0;transition:width .4s ease}\n@media (max-width:520px){.cdai{padding:16px}.cdai .cd-tl-row{grid-template-columns:minmax(0,110px) 1fr 50px;font-size:.8rem}}\n\/* game *\/\n.cdai .cd-game-card{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:12px;padding:18px;min-height:96px;font-size:1.05rem;font-weight:600;display:flex;align-items:center}\n.cdai .cd-feedback{margin-top:12px;padding:12px 14px;border-radius:10px;font-size:.93rem}\n.cdai .cd-feedback.cd-ok{background:var(--cd-good-soft);color:var(--cd-ink);border-left:4px solid var(--cd-good)}\n.cdai .cd-feedback.cd-no{background:var(--cd-bad-soft);color:var(--cd-ink);border-left:4px solid var(--cd-bad)}\n.cdai .cd-venn{position:relative;width:min(100%,300px);aspect-ratio:1\/1;margin:6px auto 0}\n.cdai .cd-venn div{position:absolute;border-radius:50%;border:2px solid var(--cd-brand);display:flex;justify-content:center;font-weight:700;font-size:.8rem;color:var(--cd-ink);padding-top:6px;transition:background .3s ease,transform .3s ease}\n.cdai .cd-venn div.cd-lit{background:var(--cd-brand-soft);transform:scale(1.03)}\n.cdai .cd-v1{inset:0}.cdai .cd-v2{inset:12%}.cdai .cd-v3{inset:26%}.cdai .cd-v4{inset:40%;align-items:center;padding-top:0!important}\n\/* checklist *\/\n.cdai.cd-check{padding:16px 18px;background:var(--cd-card)}\n.cdai.cd-check ul{list-style:none;margin:8px 0 0;padding:0}\n.cdai.cd-check li{margin:0;padding:0}\n.cdai.cd-check label{display:flex;gap:10px;align-items:flex-start;padding:7px 4px;cursor:pointer;font-size:.95rem;border-radius:8px}\n.cdai.cd-check label:hover{background:var(--cd-bg)}\n.cdai.cd-check input{width:18px;height:18px;margin-top:3px;accent-color:var(--cd-good);flex:none}\n.cdai.cd-check .cd-done{color:var(--cd-good);font-weight:700}\n\/* tokens *\/\n.cdai .cd-bars{display:flex;flex-direction:column;gap:6px;margin-top:10px}\n.cdai .cd-bar-row{display:grid;grid-template-columns:110px 1fr 52px;gap:10px;align-items:center;font-size:.9rem}\n.cdai .cd-bar-row b{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-weight:600}\n.cdai .cd-bar-row .cd-tl-bar{transition:width .35s ease}\n.cdai .cd-out{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:var(--cd-card);border:1px solid var(--cd-line);border-radius:10px;padding:12px;margin-top:12px;min-height:46px;font-size:.92rem;word-break:break-word}\n.cdai .cd-out mark{background:var(--cd-brand-soft);color:var(--cd-brand);padding:1px 4px;border-radius:4px;animation:cdpop .4s ease}\n@keyframes cdpop{from{transform:scale(1.4);opacity:0}to{transform:none;opacity:1}}\n.cdai .cd-meter{font-family:Outfit,Inter,sans-serif;font-weight:700;font-size:1.6rem;font-variant-numeric:tabular-nums}\n@media (prefers-reduced-motion:reduce){.cdai *{transition:none!important;animation:none!important}}\n.cdai .cd-tbl-wrap{overflow-x:auto;margin-top:10px}\n.cdai table.cd-tbl{border-collapse:collapse;width:100%;font-size:.88rem;font-variant-numeric:tabular-nums;background:var(--cd-card);margin:0}\n.cdai table.cd-tbl th,.cdai table.cd-tbl td{border:1px solid var(--cd-line);padding:6px 8px;text-align:center;color:var(--cd-ink)}\n.cdai table.cd-tbl th{background:var(--cd-brand-soft);font-weight:700;font-size:.8rem}\n.cdai table.cd-tbl input{width:64px;font:inherit;padding:4px 6px;border:1.5px solid var(--cd-line);border-radius:6px;background:var(--cd-bg);color:var(--cd-ink);text-align:center;margin:0}\n.cdai .cd-steps{margin-top:12px;display:grid;gap:6px;font-size:.92rem}\n.cdai .cd-steps div{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:8px;padding:8px 12px}\n.cdai .cd-steps code,.cdai .cd-eq{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9rem;background:transparent;color:var(--cd-ink);padding:0}\n.cdai .cd-eq{display:inline-block;background:var(--cd-brand-soft);color:var(--cd-brand);padding:4px 10px;border-radius:8px;font-weight:700}\n.cdai.cd-codebox{padding:0;background:#16182c;border-color:#2a2d48}\n.cdai.cd-codebox .cd-codehead{display:flex;justify-content:space-between;align-items:center;padding:8px 14px;border-bottom:1px solid #2a2d48;color:#a3a6c2;font-size:.8rem;font-weight:600}\n.cdai.cd-codebox pre{margin:0;padding:14px 16px;overflow-x:auto;background:transparent;border:0;color:#e6e7f2;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.86rem;line-height:1.6;white-space:pre}\n.cdai.cd-codebox pre code{background:transparent;color:inherit;padding:0;font:inherit}\n.cdai.cd-codebox .cd-copy{font:inherit;font-size:.78rem;font-weight:600;cursor:pointer;background:#2a2d48;color:#e6e7f2;border:0;border-radius:6px;padding:5px 10px;margin:0;text-transform:none;letter-spacing:normal}\n.cdai.cd-codebox .cd-outp{border-top:1px dashed #2a2d48;color:#8fe3b8}\n.cdai .cd-legend{display:flex;flex-wrap:wrap;gap:14px;font-size:.82rem;color:var(--cd-muted);margin-top:8px}\n.cdai .cd-legend i{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:5px;vertical-align:middle}\n.cdai canvas.cd-touch{touch-action:none;cursor:crosshair}\n.cdai canvas.cd-grab{touch-action:none;cursor:grab}\n.cdai .cd-q-opts{display:grid;gap:8px;margin-top:12px}\n.cdai .cd-q-opts button.cd-btn{text-align:left;width:100%}\n.cdai .cd-q-opts button.cd-right{border-color:var(--cd-good);background:var(--cd-good-soft)}\n.cdai .cd-q-opts button.cd-wrong{border-color:var(--cd-bad);background:var(--cd-bad-soft)}\n.cdai .cd-odds-dots{display:grid;grid-template-columns:repeat(10,1fr);gap:6px;max-width:320px;margin-top:10px}\n.cdai .cd-odds-dots i{display:block;aspect-ratio:1\/1;border-radius:50%;background:var(--cd-line);transition:background .25s ease}\n.cdai .cd-cm{display:grid;grid-template-columns:auto 1fr 1fr;gap:6px;font-size:.88rem;max-width:420px;margin-top:12px}\n.cdai .cd-cm div{padding:10px 8px;border-radius:8px;text-align:center}\n.cdai .cd-cm .cd-cm-h{color:var(--cd-muted);font-weight:600;font-size:.78rem;align-self:center}\n.cdai .cd-cm .cd-cm-c{background:var(--cd-card);border:1px solid var(--cd-line)}\n.cdai .cd-cm .cd-cm-c b{display:block;font-family:Outfit,Inter,sans-serif;font-size:1.5rem;font-variant-numeric:tabular-nums}\n.cdai .cd-cm .cd-cm-good{border-color:var(--cd-good);background:var(--cd-good-soft)}\n.cdai .cd-cm .cd-cm-bad{border-color:var(--cd-bad);background:var(--cd-bad-soft)}\n.cdai.cd-q{background:var(--cd-card);padding:18px 20px;margin:18px 0;border-left:4px solid var(--cd-brand)}\n.cdai.cd-q[hidden]{display:none!important}\n.cdai.cd-q.cd-is-known{border-left-color:var(--cd-good)}\n.cdai.cd-q .cd-q-meta{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:6px}\n.cdai .cd-pill{font-size:.72rem;font-weight:700;padding:3px 9px;border-radius:99px;background:var(--cd-brand-soft);color:var(--cd-brand);letter-spacing:.02em}\n.cdai .cd-pill.cd-lv-Freshers{background:var(--cd-good-soft);color:var(--cd-good)}\n.cdai .cd-pill.cd-lv-Experienced{background:var(--cd-bad-soft);color:var(--cd-bad)}\n.cdai.cd-q h3.cd-q-title{font-family:Outfit,Inter,sans-serif;font-size:1.15rem;line-height:1.35;margin:4px 0 10px;color:var(--cd-ink)}\n.cdai.cd-q .cd-q-body{font-size:.97rem}\n.cdai.cd-q .cd-q-body p{margin:0 0 10px}\n.cdai.cd-q .cd-q-body ul,.cdai.cd-q .cd-q-body ol{margin:0 0 10px 1.2em;padding:0}\n.cdai.cd-q .cd-q-body li{margin:3px 0}\n.cdai.cd-q .cd-q-body code,.cdai.cd-fc .cd-fc-a code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.86em;background:var(--cd-brand-soft);color:var(--cd-ink);padding:1px 5px;border-radius:4px}\n.cdai.cd-q .cd-q-body pre code,.cdai.cd-fc .cd-fc-a pre code{background:transparent;color:inherit;padding:0;font-size:inherit}\n.cdai.cd-q .cd-q-body table,.cdai.cd-fc table{border-collapse:collapse;width:100%;font-size:.88rem;margin:6px 0 12px}\n.cdai.cd-q .cd-q-body th,.cdai.cd-q .cd-q-body td,.cdai.cd-fc th,.cdai.cd-fc td{border:1px solid var(--cd-line);padding:6px 8px;text-align:left;color:var(--cd-ink)}\n.cdai.cd-q .cd-q-body th,.cdai.cd-fc th{background:var(--cd-brand-soft)}\n.cdai.cd-q .cd-codebox,.cdai.cd-fc .cd-codebox{margin:12px 0 4px}\n.cdai.cd-q .cd-q-foot{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-top:10px;flex-wrap:wrap}\n.cdai.cd-q .cd-known[aria-pressed=\"true\"]{background:var(--cd-good-soft);border-color:var(--cd-good);color:var(--cd-good)}\n.cdai.cd-q .cd-show{display:none}\n.cdai.cd-q.cd-practice:not(.cd-revealed) .cd-q-body{display:none}\n.cdai.cd-q.cd-practice:not(.cd-revealed) .cd-show{display:inline-block}\n.cdai .cd-q-top{font-size:.8rem;color:var(--cd-muted);text-decoration:none}\n.cdai.cd-pyq-tool .cd-stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:10px;margin:12px 0}\n.cdai.cd-pyq-tool select,.cdai.cd-pyq-tool input[type=search]{font:inherit;font-size:.92rem;padding:9px 12px;border:1.5px solid var(--cd-line);border-radius:10px;background:var(--cd-card);color:var(--cd-ink);margin:0;min-width:0;width:100%;height:auto}\n.cdai.cd-pyq-tool .cd-filters{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:12px}\n@media (max-width:560px){.cdai.cd-pyq-tool .cd-filters{grid-template-columns:1fr}}\n.cdai.cd-pyq-tool label.cd-tog{display:flex;align-items:center;gap:8px;font-size:.9rem;cursor:pointer}\n.cdai.cd-pyq-tool label.cd-tog input{width:18px;height:18px;accent-color:var(--cd-brand);margin:0}\n.cdai a.cd-btn{display:inline-block;text-decoration:none}\n.cdai a.cd-dl{background:var(--cd-good);border-color:var(--cd-good);color:#fff}\n.cdai.cd-fc{position:fixed;inset:0;z-index:99999;background:rgba(10,12,30,.72);display:flex;align-items:center;justify-content:center;margin:0;border:0;border-radius:0;padding:max(12px,env(safe-area-inset-top,0px)) max(12px,env(safe-area-inset-right,0px)) max(12px,env(safe-area-inset-bottom,0px)) max(12px,env(safe-area-inset-left,0px))}\n.cdai.cd-fc[hidden]{display:none}\n.cdai.cd-fc .cd-fc-card{background:var(--cd-card);color:var(--cd-ink);border-radius:16px;padding:20px;width:min(720px,100%);max-height:100%;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.35)}\n.cdai.cd-fc .cd-fc-meta{display:flex;gap:6px;margin:12px 0 6px}\n.cdai.cd-fc .cd-fc-q{font-family:Outfit,Inter,sans-serif;font-size:1.3rem;font-weight:700;line-height:1.35;margin-bottom:14px}\n.cdai.cd-fc .cd-fc-a{border-top:1px dashed var(--cd-line);padding-top:12px;margin-bottom:12px;font-size:.95rem}\n.cdai.cd-fc .cd-fc-a p{margin:0 0 10px}.cdai.cd-fc .cd-fc-a ul,.cdai.cd-fc .cd-fc-a ol{margin:0 0 10px 1.2em;padding:0}\n.cdai.cd-fc .cd-fc-actions{margin-top:6px}\n.cdai a.cd-btn{font:inherit;font-size:.92rem;font-weight:600;cursor:pointer;border-radius:10px;border:1.5px solid var(--cd-line);background:var(--cd-card);color:var(--cd-ink);padding:9px 14px;line-height:1.3;text-decoration:none;display:inline-block;transition:transform .15s ease,border-color .15s ease}\n.cdai a.cd-btn:hover{transform:translateY(-1px);border-color:var(--cd-brand)}\n.cdai a.cd-btn.cd-dl{background:#0f8a5f;border-color:#0f8a5f;color:#fff}\n.cdai a.cd-btn.cd-dl:hover{background:#0c7550}\n.cdai a.cd-btn:focus-visible{outline:3px solid var(--cd-brand);outline-offset:2px}\n<\/style>\n\n\n\n<p class=\"wp-block-paragraph\">Python is the most asked-about language in Indian tech interviews today, from campus placements at service companies to data science, backend and ML roles at product companies. The questions repeat more than you might expect: mutable vs immutable, list vs tuple, decorators, generators, the GIL, and a handful of classic coding problems.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This page collects the <strong>100 Python interview questions<\/strong> that come up most, grouped into freshers, intermediate and experienced levels. Every answer explains the concept in plain language, and every code example was run on Python 3.13 with its real output shown underneath. You can study it like a normal article, or use the tools below to filter questions, hide the answers and test yourself, revise with flashcards, and track which ones you already know. Prefer to study offline? <a href=\"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/10\/python-interview-questions-code-and-debug.pdf\">Download all 100 questions as a free PDF<\/a>.<\/p>\n\n\n\n<div class=\"cdai cd-pyq-tool\" id=\"cd-pyq-tool\">\n<span class=\"cd-tag\">Practice tools<\/span>\n<h4 class=\"cd-h\">Study these 100 questions your way<\/h4>\n<p class=\"cd-sub\">Filter, search, hide answers to test yourself, or switch to flashcards. Your progress is saved in this browser.<\/p>\n<div class=\"cd-stats\">\n<div class=\"cd-card\"><div class=\"cd-small\">Showing<\/div><div class=\"cd-stat\"><span class=\"cd-pyq-shown\">100<\/span><span style=\"font-size:1rem;color:var(--cd-muted)\"> \/ 100<\/span><\/div><\/div>\n<div class=\"cd-card\"><div class=\"cd-small\">You know<\/div><div class=\"cd-stat\"><span class=\"cd-pyq-known\">0<\/span><span style=\"font-size:1rem;color:var(--cd-muted)\"> \/ 100<\/span><\/div><div class=\"cd-prog cd-pyq-bar\"><i><\/i><\/div><\/div>\n<\/div>\n<div class=\"cd-row\" role=\"group\" aria-label=\"Level\">\n<button type=\"button\" class=\"cd-chip cd-lvl\" data-l=\"all\" aria-pressed=\"true\">All levels<\/button>\n<button type=\"button\" class=\"cd-chip cd-lvl\" data-l=\"Freshers\" aria-pressed=\"false\">Freshers (40)<\/button>\n<button type=\"button\" class=\"cd-chip cd-lvl\" data-l=\"Intermediate\" aria-pressed=\"false\">Intermediate (35)<\/button>\n<button type=\"button\" class=\"cd-chip cd-lvl\" data-l=\"Experienced\" aria-pressed=\"false\">Experienced (25)<\/button>\n<\/div>\n<div class=\"cd-filters\">\n<select class=\"cd-pyq-topic\" aria-label=\"Topic\"><option value=\"all\">All topics<\/option><\/select>\n<input type=\"search\" class=\"cd-pyq-search\" placeholder=\"Search questions, e.g. decorator\" aria-label=\"Search questions\">\n<\/div>\n<div class=\"cd-row\" style=\"margin-top:12px;gap:18px\">\n<label class=\"cd-tog\"><input type=\"checkbox\" class=\"cd-pyq-practice\"> Practice mode (hide answers)<\/label>\n<label class=\"cd-tog\"><input type=\"checkbox\" class=\"cd-pyq-hideknown\"> Hide questions I know<\/label>\n<\/div>\n<div class=\"cd-row\" style=\"margin-top:14px\">\n<button type=\"button\" class=\"cd-btn cd-primary cd-pyq-fc\">Start flashcards<\/button>\n<a class=\"cd-btn cd-dl\" href=\"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/10\/python-interview-questions-code-and-debug.pdf\" download>Download PDF (56 pages)<\/a>\n<button type=\"button\" class=\"cd-btn cd-pyq-reset\">Reset progress<\/button>\n<\/div>\n<p class=\"cd-small cd-pyq-none\" hidden style=\"margin:12px 0 0\">No questions match these filters. Try another topic or clear the search.<\/p>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-to-prepare\">How to prepare for a Python interview<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n\n<li><strong>Master the fundamentals first.<\/strong> Data types, mutability, functions and OOP make up most fresher interviews. Questions 1 to 40 cover them.<\/li>\n\n\n<li><strong>Run the code, do not just read it.<\/strong> Interviewers ask &#8220;what does this print?&#8221; constantly. Change each example and predict the output before running it.<\/li>\n\n\n<li><strong>Practise coding problems daily.<\/strong> Most Python interviews include a coding round on strings, arrays, hashing and recursion. Our <a href=\"https:\/\/codeanddebug.in\/blog\/dsa-interview-cheat-sheet\/\">DSA interview cheat sheet<\/a> lists the patterns that matter.<\/li>\n\n\n<li><strong>Know the time complexity of what you write.<\/strong> Saying &#8220;this is O(n) because the set lookup is O(1)&#8221; separates good answers from average ones. Revise with our <a href=\"https:\/\/codeanddebug.in\/blog\/time-complexity-and-space-complexity\/\">time and space complexity guide<\/a>.<\/li>\n\n\n<li><strong>Prepare for your target role.<\/strong> Data analyst and data science roles add Pandas and NumPy, backend roles add frameworks like Django or FastAPI, and senior roles add concurrency, memory and design questions.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"python-interview-questions-for-freshers\">Python interview questions for freshers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These 40 basic Python interview questions are the ones asked most often in campus placements and first job interviews. They cover the language fundamentals, data types, functions, exception handling, files and the simple coding problems that appear in almost every first round.<\/p>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-1\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q1<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">1. What is Python and what are its key features?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Python is a high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. It is known for readable code that looks close to plain English, which is why it is often the first language people learn and the default choice for data science, machine learning, automation and backend development.<\/p>\n<ul><li><strong>Easy to read and write:<\/strong> indentation instead of braces, and very little boilerplate.<\/li>\n<li><strong>Interpreted:<\/strong> you run code directly without a separate compile step.<\/li>\n<li><strong>Dynamically typed:<\/strong> you do not declare variable types.<\/li>\n<li><strong>Multi-paradigm:<\/strong> supports procedural, object-oriented and functional styles.<\/li>\n<li><strong>Huge standard library and ecosystem:<\/strong> NumPy, Pandas, Django, FastAPI, PyTorch and thousands more.<\/li>\n<li><strong>Cross-platform and open source.<\/strong><\/li><\/ul><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-2\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q2<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">2. Is Python compiled or interpreted?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Both, in a way. When you run a <code>.py<\/code> file, CPython (the standard implementation) first compiles the source code into <strong>bytecode<\/strong>, a low-level set of instructions, and caches it in <code>.pyc<\/code> files inside the <code>__pycache__<\/code> folder. The <strong>Python Virtual Machine (PVM)<\/strong> then interprets that bytecode line by line.<\/p>\n<p>Because the compile step is automatic and invisible, Python is usually called an interpreted language. You can see the bytecode with the <code>dis<\/code> module:<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import dis\n\ndef add(a, b):\n    return a + b\n\ndis.dis(add)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n  3           RESUME                   0\n\n  4           LOAD_FAST_LOAD_FAST      1 (a, b)\n              BINARY_OP                0 (+)\n              RETURN_VALUE<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-3\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q3<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">3. What is PEP 8 and why does it matter?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>PEP 8 is the official style guide for Python code. PEP stands for Python Enhancement Proposal. It covers naming, indentation, line length and spacing so that Python code written by different people looks consistent. Key rules:<\/p>\n<ul><li>Use 4 spaces per indentation level.<\/li><li>Keep lines to 79 characters (many teams allow up to 88 or 100).<\/li><li><code>snake_case<\/code> for functions and variables, <code>PascalCase<\/code> for classes, <code>UPPER_CASE<\/code> for constants.<\/li><li>Two blank lines around top-level functions and classes.<\/li><li>Imports at the top, one per line.<\/li><\/ul>\n<p>Tools like <code>black<\/code>, <code>ruff<\/code> and <code>flake8<\/code> check or auto-format code to PEP 8. Interviewers ask this to see whether you write code that a team can maintain.<\/p><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-4\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q4<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">4. What does it mean that Python is dynamically typed?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>In a dynamically typed language, the type belongs to the value, not to the variable name. You never declare a type, and the same variable can point to an integer now and a string later. Types are checked at runtime, when the code actually runs.<\/p>\n<p>Python is also <strong>strongly typed<\/strong>: it will not silently convert between unrelated types. Adding a number to a string raises an error instead of guessing what you meant.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>x = 10\nprint(type(x))\nx = &quot;ten&quot;\nprint(type(x))\n\ntry:\n    print(&quot;Age: &quot; + 25)\nexcept TypeError as e:\n    print(&quot;TypeError:&quot;, e)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n&lt;class &#x27;int&#x27;&gt;\n&lt;class &#x27;str&#x27;&gt;\nTypeError: can only concatenate str (not &quot;int&quot;) to str<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-5\" data-level=\"Freshers\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q5<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">5. What are Python&#x27;s built-in data types?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The main built-in types are:<\/p>\n<ul><li><strong>Numeric:<\/strong> <code>int<\/code>, <code>float<\/code>, <code>complex<\/code><\/li>\n<li><strong>Text:<\/strong> <code>str<\/code><\/li>\n<li><strong>Sequence:<\/strong> <code>list<\/code>, <code>tuple<\/code>, <code>range<\/code><\/li>\n<li><strong>Mapping:<\/strong> <code>dict<\/code><\/li>\n<li><strong>Set:<\/strong> <code>set<\/code>, <code>frozenset<\/code><\/li>\n<li><strong>Boolean:<\/strong> <code>bool<\/code> (a subclass of <code>int<\/code>)<\/li>\n<li><strong>Binary:<\/strong> <code>bytes<\/code>, <code>bytearray<\/code>, <code>memoryview<\/code><\/li>\n<li><strong>None type:<\/strong> <code>NoneType<\/code>, which has a single value, <code>None<\/code><\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>values = [42, 3.14, 2 + 3j, &quot;code&quot;, [1, 2], (1, 2), range(3),\n          {&quot;a&quot;: 1}, {1, 2}, frozenset({1}), True, b&quot;hi&quot;, None]\nfor v in values:\n    print(type(v).__name__, end=&quot;  &quot;)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nint  float  complex  str  list  tuple  range  dict  set  frozenset  bool  bytes  NoneType<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-6\" data-level=\"Freshers\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q6<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">6. What is the difference between mutable and immutable objects?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A <strong>mutable<\/strong> object can be changed in place after it is created. An <strong>immutable<\/strong> object cannot: any &#8220;change&#8221; creates a brand new object.<\/p>\n<ul><li>Mutable: <code>list<\/code>, <code>dict<\/code>, <code>set<\/code>, <code>bytearray<\/code>, most user-defined objects.<\/li>\n<li>Immutable: <code>int<\/code>, <code>float<\/code>, <code>str<\/code>, <code>tuple<\/code>, <code>frozenset<\/code>, <code>bytes<\/code>, <code>bool<\/code>.<\/li><\/ul>\n<p>This matters because two variables can point to the same mutable object, so changing it through one name changes what the other sees. Only immutable objects can be dictionary keys or set members.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>a = [1, 2, 3]\nb = a            # b points to the SAME list\nb.append(4)\nprint(&quot;a:&quot;, a)\n\nt = (1, 2, 3)\ntry:\n    t[0] = 99\nexcept TypeError as e:\n    print(&quot;TypeError:&quot;, e)\n\ns = &quot;code&quot;\nprint(id(s) == id(s + &quot;debug&quot;))   # concatenation makes a new string<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\na: [1, 2, 3, 4]\nTypeError: &#x27;tuple&#x27; object does not support item assignment\nFalse<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-7\" data-level=\"Freshers\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q7<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">7. What is the difference between a list and a tuple?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Both are ordered sequences that can hold any type, but:<\/p>\n<ul><li>A <strong>list<\/strong> is mutable and written with square brackets: <code>[1, 2, 3]<\/code>.<\/li>\n<li>A <strong>tuple<\/strong> is immutable and written with parentheses: <code>(1, 2, 3)<\/code>.<\/li>\n<li>Tuples use less memory and are slightly faster to create and iterate.<\/li>\n<li>Tuples are hashable (if their items are), so they can be dictionary keys. Lists cannot.<\/li><\/ul>\n<p>Use a list for a collection that will change, like a shopping cart. Use a tuple for a fixed record, like coordinates <code>(lat, lon)<\/code> or a function returning several values.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import sys\nlst = [1, 2, 3, 4, 5]\ntup = (1, 2, 3, 4, 5)\nprint(&quot;list bytes:&quot;, sys.getsizeof(lst))\nprint(&quot;tuple bytes:&quot;, sys.getsizeof(tup))\n\nlocations = {(28.61, 77.21): &quot;Delhi&quot;}   # tuple as a dict key\nprint(locations[(28.61, 77.21)])<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nlist bytes: 104\ntuple bytes: 80\nDelhi<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-8\" data-level=\"Freshers\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q8<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">8. What is a dictionary in Python, and what can be a key?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A dictionary (<code>dict<\/code>) stores key-value pairs and gives average O(1) lookup, insertion and deletion, because it is built on a hash table. Since Python 3.7, dictionaries keep the order in which keys were inserted.<\/p>\n<p>A key must be <strong>hashable<\/strong>: its hash value must never change. Strings, numbers, booleans and tuples of immutable items work as keys. Lists, dicts and sets do not.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>student = {&quot;name&quot;: &quot;Riya&quot;, &quot;branch&quot;: &quot;CSE&quot;, &quot;cgpa&quot;: 8.7}\nstudent[&quot;city&quot;] = &quot;Pune&quot;              # add\nprint(student.get(&quot;phone&quot;, &quot;N\/A&quot;))     # safe lookup with a default\nfor key, value in student.items():\n    print(key, &quot;-&gt;&quot;, value)\n\ntry:\n    bad = {[1, 2]: &quot;list key&quot;}\nexcept TypeError as e:\n    print(&quot;TypeError:&quot;, e)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nN\/A\nname -&gt; Riya\nbranch -&gt; CSE\ncgpa -&gt; 8.7\ncity -&gt; Pune\nTypeError: unhashable type: &#x27;list&#x27;<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-9\" data-level=\"Freshers\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q9<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">9. What is a set and when would you use one?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A set is an unordered collection of <strong>unique<\/strong>, hashable items. Membership checks (<code>x in s<\/code>) are O(1) on average, compared with O(n) for a list. Use a set to remove duplicates, to check membership quickly, or for mathematical operations like union and intersection.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>python_students = {&quot;Aman&quot;, &quot;Riya&quot;, &quot;Kabir&quot;, &quot;Sneha&quot;}\njava_students = {&quot;Kabir&quot;, &quot;Sneha&quot;, &quot;Arjun&quot;}\n\n# sets are unordered, so sorted() is used only to print them neatly\nprint(&quot;Both:&quot;, sorted(python_students &amp; java_students))\nprint(&quot;Either:&quot;, sorted(python_students | java_students))\nprint(&quot;Only Python:&quot;, sorted(python_students - java_students))\nprint(&quot;Unique marks:&quot;, sorted(set([90, 85, 90, 70, 85])))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nBoth: [&#x27;Kabir&#x27;, &#x27;Sneha&#x27;]\nEither: [&#x27;Aman&#x27;, &#x27;Arjun&#x27;, &#x27;Kabir&#x27;, &#x27;Riya&#x27;, &#x27;Sneha&#x27;]\nOnly Python: [&#x27;Aman&#x27;, &#x27;Riya&#x27;]\nUnique marks: [70, 85, 90]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-10\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q10<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">10. What is the difference between is and ==?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>==<\/code> checks <strong>equality<\/strong>: do the two objects have the same value? <code>is<\/code> checks <strong>identity<\/strong>: are they the exact same object in memory (same <code>id()<\/code>)?<\/p>\n<p>Use <code>==<\/code> to compare values. Use <code>is<\/code> only for singletons, most commonly <code>if x is None<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>a = [1, 2, 3]\nb = [1, 2, 3]\nc = a\nprint(a == b)   # same values\nprint(a is b)   # different objects\nprint(a is c)   # same object\n\nx = None\nprint(x is None)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nTrue\nFalse\nTrue\nTrue<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-11\" data-level=\"Freshers\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q11<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">11. What are *args and **kwargs?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>They let a function accept a variable number of arguments.<\/p>\n<ul><li><code>*args<\/code> collects extra <strong>positional<\/strong> arguments into a tuple.<\/li>\n<li><code>**kwargs<\/code> collects extra <strong>keyword<\/strong> arguments into a dictionary.<\/li><\/ul>\n<p>The names <code>args<\/code> and <code>kwargs<\/code> are only convention. The <code>*<\/code> and <code>**<\/code> do the work. The same symbols also unpack a list or dict when <em>calling<\/em> a function.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def register(name, *subjects, **details):\n    print(&quot;Name:&quot;, name)\n    print(&quot;Subjects:&quot;, subjects)\n    print(&quot;Details:&quot;, details)\n\nregister(&quot;Riya&quot;, &quot;DSA&quot;, &quot;Python&quot;, city=&quot;Pune&quot;, year=3)\n\nnums = [3, 7, 1]\nprint(max(*nums))   # unpacking a list into arguments<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nName: Riya\nSubjects: (&#x27;DSA&#x27;, &#x27;Python&#x27;)\nDetails: {&#x27;city&#x27;: &#x27;Pune&#x27;, &#x27;year&#x27;: 3}\n7<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-12\" data-level=\"Freshers\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q12<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">12. Why should you not use a mutable default argument?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Default argument values are evaluated <strong>once<\/strong>, when the function is defined, not every time it is called. If the default is a mutable object like a list, every call that relies on the default shares the same list, so data leaks between calls. This is one of the most common Python interview traps.<\/p>\n<p>The fix is to use <code>None<\/code> as the default and create a new list inside the function.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def add_item_bad(item, cart=[]):\n    cart.append(item)\n    return cart\n\nprint(add_item_bad(&quot;pen&quot;))\nprint(add_item_bad(&quot;book&quot;))   # surprise: pen is still there\n\ndef add_item(item, cart=None):\n    if cart is None:\n        cart = []\n    cart.append(item)\n    return cart\n\nprint(add_item(&quot;pen&quot;))\nprint(add_item(&quot;book&quot;))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[&#x27;pen&#x27;]\n[&#x27;pen&#x27;, &#x27;book&#x27;]\n[&#x27;pen&#x27;]\n[&#x27;book&#x27;]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-13\" data-level=\"Freshers\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q13<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">13. What is a lambda function?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A lambda is a small anonymous function written in one expression: <code>lambda arguments: expression<\/code>. It returns the value of that expression automatically. Lambdas are handy as short throwaway functions, most often as the <code>key<\/code> for sorting or with <code>map<\/code> and <code>filter<\/code>.<\/p>\n<p>If the logic needs more than one expression, or you want to reuse it, write a normal <code>def<\/code> function instead. PEP 8 discourages assigning a lambda to a name.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>students = [(&quot;Aman&quot;, 78), (&quot;Riya&quot;, 92), (&quot;Kabir&quot;, 85)]\nstudents.sort(key=lambda s: s[1], reverse=True)\nprint(students)\n\nsquare = lambda x: x * x\nprint(square(9))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[(&#x27;Riya&#x27;, 92), (&#x27;Kabir&#x27;, 85), (&#x27;Aman&#x27;, 78)]\n81<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-14\" data-level=\"Freshers\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q14<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">14. What are list, dict and set comprehensions?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Comprehensions build a new collection from an iterable in a single readable line. They are usually faster than an equivalent <code>for<\/code> loop with <code>append<\/code>, because the loop runs in optimised C code.<\/p>\n<p>The pattern is <code>[expression for item in iterable if condition]<\/code>. Use curly braces with <code>key: value<\/code> for a dict, and curly braces without a colon for a set.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>nums = range(1, 11)\nsquares = [n * n for n in nums]\nevens = [n for n in nums if n % 2 == 0]\nlengths = {word: len(word) for word in [&quot;code&quot;, &quot;and&quot;, &quot;debug&quot;]}\nfirst_letters = {word[0] for word in [&quot;apple&quot;, &quot;avocado&quot;, &quot;banana&quot;]}\n\nprint(squares)\nprint(evens)\nprint(lengths)\nprint(sorted(first_letters))   # sets have no fixed order<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n[2, 4, 6, 8, 10]\n{&#x27;code&#x27;: 4, &#x27;and&#x27;: 3, &#x27;debug&#x27;: 5}\n[&#x27;a&#x27;, &#x27;b&#x27;]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-15\" data-level=\"Freshers\" data-topic=\"Strings\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q15<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Strings<\/span><\/div><h3 class=\"cd-q-title\">15. How do you reverse a string in Python, and how does slicing work?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The simplest way is slicing with a step of -1: <code>s[::-1]<\/code>. Slicing uses <code>sequence[start:stop:step]<\/code>. <code>start<\/code> is included, <code>stop<\/code> is excluded, and any part can be omitted. Negative indices count from the end, so <code>s[-1]<\/code> is the last character.<\/p>\n<p>Slicing works on strings, lists and tuples, and always returns a new object.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>s = &quot;codeanddebug&quot;\nprint(s[::-1])      # reversed\nprint(s[0:4])       # &#x27;code&#x27;\nprint(s[-5:])       # last 5 characters\nprint(s[::2])       # every second character\nprint(&quot;&quot;.join(reversed(s)))   # another way<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\ngubeddnaedoc\ncode\ndebug\ncdadeu\ngubeddnaedoc<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-16\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q16<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">16. Why is indentation important in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Python uses indentation to define code blocks, where languages like C++ and Java use curly braces. The body of an <code>if<\/code>, a loop, a function or a class is whatever is indented under it. Wrong indentation is not a style issue: it is a syntax error, or worse, valid code that does something different from what you intended.<\/p>\n<p>PEP 8 recommends 4 spaces per level. Never mix tabs and spaces.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>marks = 72\nif marks &gt;= 40:\n    print(&quot;Passed&quot;)\n    print(&quot;Certificate issued&quot;)   # inside the if\nprint(&quot;Result processed&quot;)          # outside the if, always runs<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nPassed\nCertificate issued\nResult processed<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-17\" data-level=\"Freshers\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q17<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">17. What is the difference between append() and extend()?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>append(x)<\/code> adds <code>x<\/code> as a <strong>single<\/strong> element at the end of the list, even if <code>x<\/code> is itself a list. <code>extend(iterable)<\/code> adds <strong>each element<\/strong> of the iterable one by one. <code>insert(i, x)<\/code> adds an element at a specific position.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>a = [1, 2]\na.append([3, 4])\nprint(a)\n\nb = [1, 2]\nb.extend([3, 4])\nprint(b)\n\nc = [1, 2]\nc.insert(0, 0)\nprint(c)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[1, 2, [3, 4]]\n[1, 2, 3, 4]\n[0, 1, 2]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-18\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q18<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">18. What do pass, break and continue do?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><code>pass<\/code> does nothing. It is a placeholder where Python requires a statement, like an empty function or class you will fill in later.<\/li>\n<li><code>break<\/code> exits the nearest loop immediately.<\/li>\n<li><code>continue<\/code> skips the rest of the current iteration and moves to the next one.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def todo():\n    pass   # implement later\n\nfor n in range(1, 10):\n    if n % 2 == 0:\n        continue    # skip even numbers\n    if n &gt; 7:\n        break       # stop the loop\n    print(n, end=&quot; &quot;)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n1 3 5 7<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-19\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q19<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">19. What is None in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>None<\/code> is a special constant that represents the absence of a value. It is the only instance of <code>NoneType<\/code>. Functions that do not explicitly return anything return <code>None<\/code>. It is falsy in boolean context, but it is not the same as <code>0<\/code>, <code>False<\/code> or an empty string.<\/p>\n<p>Always check for it with <code>is None<\/code>, not <code>== None<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def greet(name):\n    print(&quot;Hello&quot;, name)\n\nresult = greet(&quot;Riya&quot;)\nprint(result)\nprint(result is None)\nprint(bool(None), None == 0, None == False)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nHello Riya\nNone\nTrue\nFalse False False<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-20\" data-level=\"Freshers\" data-topic=\"Strings\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q20<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Strings<\/span><\/div><h3 class=\"cd-q-title\">20. Are strings mutable? Name some useful string methods.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>No, strings are immutable. Every string method returns a <strong>new<\/strong> string and leaves the original unchanged. Commonly asked methods:<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>s = &quot;  Code and Debug  &quot;\nprint(s.strip())\nprint(s.lower(), &quot;|&quot;, s.upper())\nprint(s.strip().split(&quot; &quot;))\nprint(&quot;-&quot;.join([&quot;2026&quot;, &quot;10&quot;, &quot;17&quot;]))\nprint(&quot;python&quot;.replace(&quot;py&quot;, &quot;Py&quot;))\nprint(&quot;data.csv&quot;.endswith(&quot;.csv&quot;), &quot;Riya&quot;.startswith(&quot;R&quot;))\nprint(&quot;banana&quot;.count(&quot;a&quot;), &quot;banana&quot;.find(&quot;n&quot;))\nprint(&quot;42&quot;.isdigit(), &quot;abc&quot;.isalpha())<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nCode and Debug\n  code and debug   |   CODE AND DEBUG  \n[&#x27;Code&#x27;, &#x27;and&#x27;, &#x27;Debug&#x27;]\n2026-10-17\nPython\nTrue True\n3 2\nTrue True<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-21\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q21<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">21. What is type conversion (casting) in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Type conversion changes a value from one type to another. <strong>Implicit<\/strong> conversion happens automatically when it is safe, for example <code>int + float<\/code> gives a <code>float<\/code>. <strong>Explicit<\/strong> conversion (casting) uses constructor functions like <code>int()<\/code>, <code>float()<\/code>, <code>str()<\/code>, <code>list()<\/code>, <code>tuple()<\/code> and <code>set()<\/code>. Invalid conversions raise a <code>ValueError<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>print(5 + 2.5)               # implicit: int -&gt; float\nprint(int(&quot;42&quot;) + 1)\nprint(float(&quot;3.5&quot;))\nprint(int(9.99))             # truncates, does not round\nprint(list(&quot;abc&quot;), tuple([1, 2]), sorted(set(&quot;hello&quot;)))\ntry:\n    int(&quot;forty&quot;)\nexcept ValueError as e:\n    print(&quot;ValueError:&quot;, e)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n7.5\n43\n3.5\n9\n[&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;] (1, 2) [&#x27;e&#x27;, &#x27;h&#x27;, &#x27;l&#x27;, &#x27;o&#x27;]\nValueError: invalid literal for int() with base 10: &#x27;forty&#x27;<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-22\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q22<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">22. What is the difference between \/, \/\/ and %?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><code>\/<\/code> is true division and always returns a float.<\/li>\n<li><code>\/\/<\/code> is floor division: it divides and rounds <strong>down<\/strong> to the nearest whole number.<\/li>\n<li><code>%<\/code> is modulo: the remainder.<\/li><\/ul>\n<p>The tricky part is negative numbers. Floor division rounds towards negative infinity, not towards zero, so <code>-7 \/\/ 2<\/code> is <code>-4<\/code>. The result of <code>%<\/code> always has the same sign as the divisor.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>print(7 \/ 2, 7 \/\/ 2, 7 % 2)\nprint(-7 \/ 2, -7 \/\/ 2, -7 % 2)\nprint(divmod(17, 5))     # (quotient, remainder) in one call<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n3.5 3 1\n-3.5 -4 1\n(3, 2)<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-23\" data-level=\"Freshers\" data-topic=\"Memory\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q23<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Memory<\/span><\/div><h3 class=\"cd-q-title\">23. How does Python manage memory?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Python manages memory automatically through a private heap that the interpreter controls. Two mechanisms free memory you no longer use:<\/p>\n<ul><li><strong>Reference counting:<\/strong> every object tracks how many references point to it. When the count drops to zero, the memory is freed immediately.<\/li>\n<li><strong>Cyclic garbage collector:<\/strong> reference counting cannot free objects that refer to each other in a cycle, so the <code>gc<\/code> module periodically finds and cleans up such cycles.<\/li><\/ul>\n<p>Small objects are allocated by an optimised allocator called pymalloc. As a developer you rarely manage memory yourself, but you should avoid holding references to large objects longer than needed.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import sys, gc\n\ndata = [1, 2, 3]\nprint(sys.getrefcount(data))   # includes the temporary reference from the call\nalias = data\nprint(sys.getrefcount(data))   # one more reference now\ndel alias\nprint(sys.getrefcount(data))\nprint(&quot;GC enabled:&quot;, gc.isenabled())<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n2\n3\n2\nGC enabled: True<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-24\" data-level=\"Freshers\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q24<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">24. What are local and global variables? When do you need the global keyword?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A variable created inside a function is <strong>local<\/strong> to it. A variable created at the top level of a module is <strong>global<\/strong>. A function can <em>read<\/em> a global variable freely, but if it <em>assigns<\/em> to that name, Python treats it as a new local variable unless you declare it with <code>global<\/code>. For variables in an enclosing function, use <code>nonlocal<\/code>.<\/p>\n<p>Modifying globals makes code hard to test, so prefer returning values instead.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>count = 0\n\ndef increment_wrong():\n    try:\n        count += 1\n    except UnboundLocalError as e:\n        print(&quot;UnboundLocalError:&quot;, e)\n\ndef increment():\n    global count\n    count += 1\n\nincrement_wrong()\nincrement()\nincrement()\nprint(&quot;count =&quot;, count)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nUnboundLocalError: cannot access local variable &#x27;count&#x27; where it is not associated with a value\ncount = 2<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-25\" data-level=\"Freshers\" data-topic=\"Modules\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q25<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Modules<\/span><\/div><h3 class=\"cd-q-title\">25. What is the difference between a module and a package?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A <strong>module<\/strong> is a single <code>.py<\/code> file containing functions, classes and variables. A <strong>package<\/strong> is a folder of modules, which can contain sub-packages. Traditionally a package has an <code>__init__.py<\/code> file, which runs when the package is imported. Since Python 3.3, folders without it can also work as &#8220;namespace packages&#8221;.<\/p>\n<p>A <strong>library<\/strong> is a broader term for a collection of packages, like NumPy. You import them with <code>import module<\/code>, <code>from package import module<\/code> or <code>import numpy as np<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import math\nfrom collections import Counter\nimport json as js\n\nprint(math.sqrt(144))\nprint(Counter(&quot;mississippi&quot;).most_common(2))\nprint(js.dumps({&quot;ok&quot;: True}))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n12.0\n[(&#x27;i&#x27;, 4), (&#x27;s&#x27;, 4)]\n{&quot;ok&quot;: true}<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-26\" data-level=\"Freshers\" data-topic=\"Modules\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q26<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Modules<\/span><\/div><h3 class=\"cd-q-title\">26. What does if __name__ == &quot;__main__&quot; do?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Every module has a built-in variable <code>__name__<\/code>. When you run a file directly, Python sets it to <code>\"__main__\"<\/code>. When the file is imported by another file, <code>__name__<\/code> is the module&#8217;s name instead.<\/p>\n<p>Putting code under <code>if __name__ == \"__main__\":<\/code> makes it run only when the file is executed directly, not on import. This lets one file work both as a reusable module and as a script, and it keeps test or demo code from running when someone imports your functions.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def calculate_gst(amount, rate=0.18):\n    return round(amount * rate, 2)\n\nif __name__ == &quot;__main__&quot;:\n    print(&quot;Running directly, __name__ is&quot;, __name__)\n    print(&quot;GST on 1000:&quot;, calculate_gst(1000))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nRunning directly, __name__ is __main__\nGST on 1000: 180.0<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-27\" data-level=\"Freshers\" data-topic=\"Exceptions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q27<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Exceptions<\/span><\/div><h3 class=\"cd-q-title\">27. How does exception handling work in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Exceptions are handled with <code>try<\/code>, <code>except<\/code>, <code>else<\/code> and <code>finally<\/code>:<\/p>\n<ul><li><code>try<\/code>: code that might fail.<\/li>\n<li><code>except<\/code>: runs if a matching exception occurs. Catch specific exceptions, not a bare <code>except:<\/code>.<\/li>\n<li><code>else<\/code>: runs only if no exception occurred.<\/li>\n<li><code>finally<\/code>: always runs, used for clean-up like closing a connection.<\/li><\/ul>\n<p>Use <code>raise<\/code> to throw an exception yourself.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def safe_divide(a, b):\n    try:\n        result = a \/ b\n    except ZeroDivisionError:\n        print(&quot;Cannot divide by zero&quot;)\n        return None\n    except TypeError as e:\n        print(&quot;Bad input:&quot;, e)\n        return None\n    else:\n        print(&quot;Division successful&quot;)\n        return result\n    finally:\n        print(&quot;Done&quot;)\n\nprint(safe_divide(10, 2))\nprint(safe_divide(10, 0))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nDivision successful\nDone\n5.0\nCannot divide by zero\nDone\nNone<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-28\" data-level=\"Freshers\" data-topic=\"Files\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q28<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Files<\/span><\/div><h3 class=\"cd-q-title\">28. How do you read and write files in Python? Why use with?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Use the built-in <code>open(path, mode)<\/code> with modes like <code>\"r\"<\/code> (read), <code>\"w\"<\/code> (write, overwrites), <code>\"a\"<\/code> (append) and <code>\"b\"<\/code> for binary. The <code>with<\/code> statement is a context manager that <strong>automatically closes the file<\/strong>, even if an error occurs, so you never leak file handles.<\/p>\n<p>Always pass <code>encoding=\"utf-8\"<\/code> for text files so behaviour is the same on Windows and Linux.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>with open(&quot;notes.txt&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:\n    f.write(&quot;Python\\nDSA\\nSQL\\n&quot;)\n\nwith open(&quot;notes.txt&quot;, encoding=&quot;utf-8&quot;) as f:\n    for line_no, line in enumerate(f, start=1):\n        print(line_no, line.strip())\n\nprint(f.closed)   # True: closed automatically<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n1 Python\n2 DSA\n3 SQL\nTrue<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-29\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q29<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">29. What do enumerate() and zip() do?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>enumerate(iterable, start=0)<\/code> gives you the index and the item together, so you do not need a manual counter. <code>zip(a, b, ...)<\/code> walks through several iterables in parallel and yields tuples. It stops at the shortest one (use <code>itertools.zip_longest<\/code> to go to the longest, or <code>strict=True<\/code> in Python 3.10+ to raise an error on unequal lengths).<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>names = [&quot;Aman&quot;, &quot;Riya&quot;, &quot;Kabir&quot;]\nmarks = [78, 92, 85]\n\nfor rank, name in enumerate(names, start=1):\n    print(rank, name)\n\nfor name, mark in zip(names, marks):\n    print(f&quot;{name}: {mark}&quot;)\n\nprint(dict(zip(names, marks)))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n1 Aman\n2 Riya\n3 Kabir\nAman: 78\nRiya: 92\nKabir: 85\n{&#x27;Aman&#x27;: 78, &#x27;Riya&#x27;: 92, &#x27;Kabir&#x27;: 85}<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-30\" data-level=\"Freshers\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q30<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">30. What is range() and why is it memory efficient?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>range(start, stop, step)<\/code> represents a sequence of integers. It does not store all the numbers. It calculates each value when needed, so <code>range(10**9)<\/code> takes the same tiny amount of memory as <code>range(10)<\/code>. It supports indexing, slicing, <code>len()<\/code> and fast membership tests.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import sys\nr = range(0, 20, 3)\nprint(list(r))\nprint(r[2], len(r), 9 in r)\nprint(sys.getsizeof(range(10)), sys.getsizeof(range(10**9)))\nprint(sys.getsizeof(list(range(1000))))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[0, 3, 6, 9, 12, 15, 18]\n6 7 True\n48 48\n8056<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-31\" data-level=\"Freshers\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q31<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">31. What is the difference between a shallow copy and a deep copy?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A <strong>shallow copy<\/strong> creates a new outer object but fills it with <strong>references<\/strong> to the same inner objects. A <strong>deep copy<\/strong> recursively copies everything, so the new object is completely independent. The difference only matters for nested mutable objects, like a list of lists.<\/p>\n<p>Shallow copy: <code>list.copy()<\/code>, <code>list(a)<\/code>, <code>a[:]<\/code> or <code>copy.copy()<\/code>. Deep copy: <code>copy.deepcopy()<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import copy\noriginal = [[1, 2], [3, 4]]\nshallow = copy.copy(original)\ndeep = copy.deepcopy(original)\n\noriginal[0].append(99)\nprint(&quot;original:&quot;, original)\nprint(&quot;shallow: &quot;, shallow)   # inner list is shared\nprint(&quot;deep:    &quot;, deep)      # fully independent<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\noriginal: [[1, 2, 99], [3, 4]]\nshallow:  [[1, 2, 99], [3, 4]]\ndeep:     [[1, 2], [3, 4]]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-32\" data-level=\"Freshers\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q32<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">32. What is a docstring?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A docstring is a string literal written as the first statement of a module, function, class or method. It documents what the code does and is stored in the object&#8217;s <code>__doc__<\/code> attribute, so tools like <code>help()<\/code>, IDEs and documentation generators can read it. Use triple quotes, and describe the purpose, parameters and return value.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def bmi(weight_kg, height_m):\n    &quot;&quot;&quot;Return body mass index rounded to 1 decimal.\n\n    weight_kg: weight in kilograms\n    height_m: height in metres\n    &quot;&quot;&quot;\n    return round(weight_kg \/ height_m ** 2, 1)\n\nprint(bmi(68, 1.72))\nprint(bmi.__doc__.splitlines()[0])<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n23.0\nReturn body mass index rounded to 1 decimal.<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-33\" data-level=\"Freshers\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q33<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">33. What are namespaces and the LEGB rule?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A namespace is a mapping from names to objects. When Python looks up a name, it searches four scopes in order, known as <strong>LEGB<\/strong>:<\/p>\n<ol><li><strong>Local:<\/strong> inside the current function.<\/li><li><strong>Enclosing:<\/strong> inside any outer function, for nested functions.<\/li><li><strong>Global:<\/strong> the module level.<\/li><li><strong>Built-in:<\/strong> names like <code>len<\/code> and <code>print<\/code>.<\/li><\/ol>\n<p>The first match wins. That is why shadowing a built-in, such as naming a variable <code>list<\/code>, breaks later code that calls <code>list()<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>x = &quot;global&quot;\n\ndef outer():\n    x = &quot;enclosing&quot;\n    def inner():\n        x = &quot;local&quot;\n        print(x)\n    inner()\n    print(x)\n\nouter()\nprint(x)\nprint(len(&quot;LEGB&quot;))   # found in built-ins<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nlocal\nenclosing\nglobal\n4<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-34\" data-level=\"Freshers\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q34<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">34. How do you remove duplicates from a list while keeping the order?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>set(lst)<\/code> removes duplicates but does not keep the original order. Since dictionaries preserve insertion order, <code>dict.fromkeys(lst)<\/code> is the cleanest one-liner that keeps order. A manual loop with a <code>seen<\/code> set also works and is easy to explain in an interview. Both run in O(n).<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>cities = [&quot;Pune&quot;, &quot;Delhi&quot;, &quot;Pune&quot;, &quot;Surat&quot;, &quot;Delhi&quot;, &quot;Goa&quot;]\n\nprint(list(dict.fromkeys(cities)))\n\nseen, result = set(), []\nfor c in cities:\n    if c not in seen:\n        seen.add(c)\n        result.append(c)\nprint(result)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[&#x27;Pune&#x27;, &#x27;Delhi&#x27;, &#x27;Surat&#x27;, &#x27;Goa&#x27;]\n[&#x27;Pune&#x27;, &#x27;Delhi&#x27;, &#x27;Surat&#x27;, &#x27;Goa&#x27;]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-35\" data-level=\"Freshers\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q35<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">35. Write a program to check whether a string is a palindrome.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A palindrome reads the same forwards and backwards, like &#8220;madam&#8221; or &#8220;racecar&#8221;. The simplest check compares the string with its reverse. For sentences, first remove non-alphanumeric characters and ignore case. The two-pointer version uses O(1) extra space and is often what interviewers want next. We cover the number version in detail in our <a href=\"https:\/\/codeanddebug.in\/blog\/palindrome-number-program-in-python\/\">palindrome program in Python<\/a> guide.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def is_palindrome(s):\n    clean = &quot;&quot;.join(ch.lower() for ch in s if ch.isalnum())\n    return clean == clean[::-1]\n\ndef is_palindrome_two_pointer(s):\n    i, j = 0, len(s) - 1\n    while i &lt; j:\n        if s[i] != s[j]:\n            return False\n        i += 1\n        j -= 1\n    return True\n\nprint(is_palindrome(&quot;A man, a plan, a canal: Panama&quot;))\nprint(is_palindrome_two_pointer(&quot;racecar&quot;), is_palindrome_two_pointer(&quot;python&quot;))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nTrue\nTrue False<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-36\" data-level=\"Freshers\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q36<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">36. How do you count the frequency of each character or word?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Use <code>collections.Counter<\/code>, which is a dict subclass built for counting. It also gives you <code>most_common(n)<\/code>. You can do the same with a plain dict and <code>get()<\/code>, which interviewers sometimes ask for to see that you understand the logic.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from collections import Counter\n\ntext = &quot;to be or not to be&quot;\nprint(Counter(text.split()))\nprint(Counter(&quot;hello&quot;).most_common(1))\n\nfreq = {}\nfor ch in &quot;banana&quot;:\n    freq[ch] = freq.get(ch, 0) + 1\nprint(freq)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nCounter({&#x27;to&#x27;: 2, &#x27;be&#x27;: 2, &#x27;or&#x27;: 1, &#x27;not&#x27;: 1})\n[(&#x27;l&#x27;, 2)]\n{&#x27;b&#x27;: 1, &#x27;a&#x27;: 3, &#x27;n&#x27;: 2}<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-37\" data-level=\"Freshers\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q37<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">37. How do you swap two variables in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Python lets you swap in one line with tuple packing and unpacking: <code>a, b = b, a<\/code>. The right side builds a tuple first, then unpacks it into the names on the left, so no temporary variable is needed. Interviewers may also ask for the arithmetic or XOR trick, which only works for numbers.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>a, b = 5, 10\na, b = b, a\nprint(a, b)\n\nx, y = 3, 7\nx = x + y\ny = x - y\nx = x - y\nprint(x, y)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n10 5\n7 3<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-38\" data-level=\"Freshers\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q38<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">38. Find the largest and second largest number in a list.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The easy way is <code>sorted(set(nums))<\/code>, but that is O(n log n). The single-pass approach tracks the top two values as you go, in O(n) time and O(1) space. Handle duplicates and lists with fewer than two distinct values.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def top_two(nums):\n    first = second = float(&quot;-inf&quot;)\n    for n in nums:\n        if n &gt; first:\n            first, second = n, first\n        elif first &gt; n &gt; second:\n            second = n\n    return first, (second if second != float(&quot;-inf&quot;) else None)\n\nprint(top_two([12, 45, 2, 41, 45, 30]))\nprint(top_two([7, 7, 7]))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n(45, 41)\n(7, None)<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-39\" data-level=\"Freshers\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q39<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">39. Write a function to check whether a number is prime.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A prime number is greater than 1 and divisible only by 1 and itself. You only need to test divisors up to the square root of n, because any factor larger than the square root pairs with one smaller than it. That brings the time down to O(\u221an). Skipping even numbers after 2 halves the work again.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import math\n\ndef is_prime(n):\n    if n &lt; 2:\n        return False\n    if n in (2, 3):\n        return True\n    if n % 2 == 0:\n        return False\n    for d in range(3, math.isqrt(n) + 1, 2):\n        if n % d == 0:\n            return False\n    return True\n\nprint([n for n in range(1, 40) if is_prime(n)])\nprint(is_prime(97), is_prime(1_000_003))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]\nTrue True<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-40\" data-level=\"Freshers\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q40<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">40. Print the Fibonacci series up to n terms.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Each Fibonacci number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8 and so on. The iterative solution runs in O(n) time and O(1) extra space. The naive recursive version is O(2^n) and is a classic example of why memoisation matters (see the <code>lru_cache<\/code> question later). A generator is a neat Pythonic version.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def fibonacci(n):\n    a, b = 0, 1\n    for _ in range(n):\n        yield a\n        a, b = b, a + b\n\nprint(list(fibonacci(12)))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"intermediate-python-interview-questions\">Intermediate Python interview questions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These 35 questions are asked once the basics are clear, usually for candidates with some project or internship experience: iterators and generators, decorators and closures, object-oriented programming, context managers, the collections module, JSON and files, plus classic coding questions like Two Sum.<\/p>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-41\" data-level=\"Intermediate\" data-topic=\"Iterators &amp; generators\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q41<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Iterators &amp; generators<\/span><\/div><h3 class=\"cd-q-title\">41. What is the difference between an iterable and an iterator?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>An <strong>iterable<\/strong> is any object you can loop over, such as a list, string, dict or file. It has an <code>__iter__()<\/code> method that returns an iterator. An <strong>iterator<\/strong> is the object that actually produces values one at a time through <code>__next__()<\/code>, and raises <code>StopIteration<\/code> when it runs out. Iterators remember their position and can only be consumed once.<\/p>\n<p>A <code>for<\/code> loop calls <code>iter()<\/code> on the iterable, then calls <code>next()<\/code> repeatedly until <code>StopIteration<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>nums = [10, 20, 30]          # iterable\nit = iter(nums)              # iterator\nprint(next(it), next(it), next(it))\ntry:\n    next(it)\nexcept StopIteration:\n    print(&quot;StopIteration: iterator exhausted&quot;)\n\nclass Countdown:\n    def __init__(self, start):\n        self.current = start\n    def __iter__(self):\n        return self\n    def __next__(self):\n        if self.current &lt;= 0:\n            raise StopIteration\n        self.current -= 1\n        return self.current + 1\n\nprint(list(Countdown(5)))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n10 20 30\nStopIteration: iterator exhausted\n[5, 4, 3, 2, 1]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-42\" data-level=\"Intermediate\" data-topic=\"Iterators &amp; generators\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q42<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Iterators &amp; generators<\/span><\/div><h3 class=\"cd-q-title\">42. What is a generator and how does yield work?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A generator is a function that uses <code>yield<\/code> instead of <code>return<\/code>. Calling it does not run the body. It returns a generator object, which is an iterator. Each <code>next()<\/code> runs the function until the next <code>yield<\/code>, hands back that value, and <strong>pauses<\/strong>, keeping all local variables. The next call resumes right after the <code>yield<\/code>.<\/p>\n<p>Generators produce values lazily, one at a time, so they can handle huge or even infinite sequences with almost no memory.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def read_in_batches(items, size):\n    for i in range(0, len(items), size):\n        print(f&quot;  (producing batch starting at {i})&quot;)\n        yield items[i:i + size]\n\ngen = read_in_batches(list(range(1, 8)), 3)\nprint(type(gen).__name__)\nfor batch in gen:\n    print(batch)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\ngenerator\n  (producing batch starting at 0)\n[1, 2, 3]\n  (producing batch starting at 3)\n[4, 5, 6]\n  (producing batch starting at 6)\n[7]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-43\" data-level=\"Intermediate\" data-topic=\"Iterators &amp; generators\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q43<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Iterators &amp; generators<\/span><\/div><h3 class=\"cd-q-title\">43. What is the difference between a list comprehension and a generator expression?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>They look almost identical, but a list comprehension uses square brackets and builds the <strong>entire list in memory<\/strong> right away. A generator expression uses parentheses and produces items <strong>lazily<\/strong>, one at a time, using a tiny fixed amount of memory. Use a generator expression when you only need to iterate once, for example inside <code>sum()<\/code>, <code>max()<\/code> or <code>any()<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import sys\nsquares_list = [n * n for n in range(1_000_000)]\nsquares_gen = (n * n for n in range(1_000_000))\n\nprint(&quot;list bytes:&quot;, sys.getsizeof(squares_list))\nprint(&quot;generator bytes:&quot;, sys.getsizeof(squares_gen))\nprint(sum(n * n for n in range(1_000_000)))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nlist bytes: 8448728\ngenerator bytes: 200\n333332833333500000<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-44\" data-level=\"Intermediate\" data-topic=\"Decorators\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q44<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Decorators<\/span><\/div><h3 class=\"cd-q-title\">44. What is a decorator in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A decorator is a function that takes another function and returns a new function that adds behaviour before or after it, without changing the original code. Writing <code>@decorator<\/code> above a function is shorthand for <code>func = decorator(func)<\/code>. Decorators are used for logging, timing, authentication checks, caching and input validation. Flask&#8217;s <code>@app.route<\/code> and Python&#8217;s <code>@property<\/code> are decorators.<\/p>\n<p>Always use <code>functools.wraps<\/code> inside your decorator so the wrapped function keeps its name and docstring.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from functools import wraps\n\ndef log_call(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        print(f&quot;Calling {func.__name__} with {args} {kwargs}&quot;)\n        result = func(*args, **kwargs)\n        print(f&quot;{func.__name__} returned {result}&quot;)\n        return result\n    return wrapper\n\n@log_call\ndef total_price(price, qty, discount=0):\n    return price * qty - discount\n\ntotal_price(250, 3, discount=50)\nprint(total_price.__name__)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nCalling total_price with (250, 3) {&#x27;discount&#x27;: 50}\ntotal_price returned 700\ntotal_price<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-45\" data-level=\"Intermediate\" data-topic=\"Decorators\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q45<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Decorators<\/span><\/div><h3 class=\"cd-q-title\">45. How do you write a decorator that takes arguments?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>You add one more level of nesting. The outer function receives the decorator&#8217;s arguments and returns the actual decorator, which then receives the function. So <code>@retry(times=3)<\/code> first calls <code>retry(times=3)<\/code>, and the result is applied to the function.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from functools import wraps\n\ndef retry(times):\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            for attempt in range(1, times + 1):\n                try:\n                    return func(*args, **kwargs)\n                except ConnectionError as e:\n                    print(f&quot;Attempt {attempt} failed: {e}&quot;)\n            raise RuntimeError(f&quot;Failed after {times} attempts&quot;)\n        return wrapper\n    return decorator\n\ncalls = {&quot;n&quot;: 0}\n\n@retry(times=3)\ndef fetch_data():\n    calls[&quot;n&quot;] += 1\n    if calls[&quot;n&quot;] &lt; 3:\n        raise ConnectionError(&quot;server busy&quot;)\n    return &quot;data received&quot;\n\nprint(fetch_data())<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nAttempt 1 failed: server busy\nAttempt 2 failed: server busy\ndata received<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-46\" data-level=\"Intermediate\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q46<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">46. What is a closure?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A closure is an inner function that remembers variables from the enclosing function&#8217;s scope, even after the outer function has finished running. Three conditions: there is a nested function, it refers to a variable from the outer function, and the outer function returns the inner one.<\/p>\n<p>Closures let you keep private state without writing a class, and they are the mechanism that makes decorators work.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def make_counter():\n    count = 0\n    def counter():\n        nonlocal count\n        count += 1\n        return count\n    return counter\n\nc1 = make_counter()\nc2 = make_counter()\nprint(c1(), c1(), c1())\nprint(c2())\nprint(c1.__closure__[0].cell_contents)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n1 2 3\n1\n3<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-47\" data-level=\"Intermediate\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q47<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">47. Explain map(), filter() and reduce().<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><code>map(func, iterable)<\/code> applies a function to every item.<\/li>\n<li><code>filter(func, iterable)<\/code> keeps only the items for which the function returns <code>True<\/code>.<\/li>\n<li><code>reduce(func, iterable)<\/code> from <code>functools<\/code> combines items into a single value by applying the function cumulatively.<\/li><\/ul>\n<p><code>map<\/code> and <code>filter<\/code> return lazy iterators in Python 3. In most code, list comprehensions are considered more readable than <code>map<\/code> and <code>filter<\/code> with lambdas.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from functools import reduce\n\nprices = [120, 450, 80, 999, 300]\nwith_gst = list(map(lambda p: round(p * 1.18, 2), prices))\nexpensive = list(filter(lambda p: p &gt; 200, prices))\ntotal = reduce(lambda a, b: a + b, prices)\n\nprint(with_gst)\nprint(expensive)\nprint(total)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[141.6, 531.0, 94.4, 1178.82, 354.0]\n[450, 999, 300]\n1949<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-48\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q48<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">48. What are the four pillars of OOP, and how does Python support them?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><strong>Encapsulation:<\/strong> bundling data and methods in a class and restricting direct access. Python uses naming conventions (<code>_protected<\/code>, <code>__private<\/code>) and properties, not strict access modifiers.<\/li>\n<li><strong>Abstraction:<\/strong> exposing only what the user needs and hiding details. Python provides abstract base classes through the <code>abc<\/code> module.<\/li>\n<li><strong>Inheritance:<\/strong> a class can reuse and extend another class. Python supports single, multiple and multilevel inheritance.<\/li>\n<li><strong>Polymorphism:<\/strong> the same interface works for different types, through method overriding, operator overloading with dunder methods, and duck typing.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class Payment:\n    def pay(self, amount):\n        raise NotImplementedError\n\nclass UPI(Payment):\n    def pay(self, amount):\n        return f&quot;Paid Rs {amount} via UPI&quot;\n\nclass Card(Payment):\n    def pay(self, amount):\n        return f&quot;Paid Rs {amount} via card&quot;\n\nfor method in [UPI(), Card()]:\n    print(method.pay(499))   # same call, different behaviour<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nPaid Rs 499 via UPI\nPaid Rs 499 via card<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-49\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q49<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">49. What is the difference between class variables and instance variables?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A <strong>class variable<\/strong> is defined directly in the class body and is shared by all instances. An <strong>instance variable<\/strong> is set on <code>self<\/code>, usually in <code>__init__<\/code>, and each object gets its own copy. Assigning to a class variable through an instance creates a new instance variable that hides the class one, which is a common source of bugs.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class Student:\n    college = &quot;IIT Bombay&quot;          # class variable\n    def __init__(self, name):\n        self.name = name            # instance variable\n\na, b = Student(&quot;Aman&quot;), Student(&quot;Riya&quot;)\nprint(a.college, b.college)\nStudent.college = &quot;IIT Delhi&quot;\nprint(a.college, b.college)\na.college = &quot;NIT Surat&quot;            # creates an instance variable on a only\nprint(a.college, b.college, Student.college)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nIIT Bombay IIT Bombay\nIIT Delhi IIT Delhi\nNIT Surat IIT Delhi IIT Delhi<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-50\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q50<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">50. What are __init__ and self?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>__init__<\/code> is the initialiser method that runs automatically right after a new object is created. It sets up the object&#8217;s initial state. Strictly speaking, the constructor that creates the object is <code>__new__<\/code>, and <code>__init__<\/code> then initialises it.<\/p>\n<p><code>self<\/code> is the first parameter of every instance method and refers to the current object. Python passes it automatically, so <code>obj.method(x)<\/code> is really <code>Class.method(obj, x)<\/code>. The name <code>self<\/code> is only a convention.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class BankAccount:\n    def __init__(self, owner, balance=0):\n        self.owner = owner\n        self.balance = balance\n\n    def deposit(self, amount):\n        self.balance += amount\n        return self.balance\n\nacc = BankAccount(&quot;Kabir&quot;, 1000)\nprint(acc.deposit(500))\nprint(BankAccount.deposit(acc, 250))   # what Python does behind the scenes<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n1500\n1750<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-51\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q51<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">51. How does inheritance work, and what does super() do?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Inheritance lets a child class reuse the attributes and methods of a parent class and override or extend them. <code>super()<\/code> returns a proxy to the next class in the method resolution order, so you can call the parent&#8217;s version of a method, most commonly the parent&#8217;s <code>__init__<\/code>, without hard-coding the parent&#8217;s name.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class Employee:\n    def __init__(self, name, salary):\n        self.name = name\n        self.salary = salary\n    def describe(self):\n        return f&quot;{self.name} earns {self.salary}&quot;\n\nclass Manager(Employee):\n    def __init__(self, name, salary, team_size):\n        super().__init__(name, salary)\n        self.team_size = team_size\n    def describe(self):\n        return super().describe() + f&quot; and manages {self.team_size} people&quot;\n\nprint(Manager(&quot;Sneha&quot;, 150000, 8).describe())\nprint(issubclass(Manager, Employee))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nSneha earns 150000 and manages 8 people\nTrue<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-52\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q52<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">52. What is the Method Resolution Order (MRO)?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The MRO is the order in which Python searches classes for a method or attribute, which matters with multiple inheritance. Python uses the <strong>C3 linearisation<\/strong> algorithm, which guarantees that a child comes before its parents and that the order of parents in the class definition is respected. This solves the &#8220;diamond problem&#8221;, where two parents share a common grandparent. You can inspect it with <code>ClassName.__mro__<\/code> or <code>ClassName.mro()<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class A:\n    def hello(self): return &quot;A&quot;\nclass B(A):\n    def hello(self): return &quot;B&quot;\nclass C(A):\n    def hello(self): return &quot;C&quot;\nclass D(B, C):\n    pass\n\nprint(D().hello())\nprint([cls.__name__ for cls in D.__mro__])<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nB\n[&#x27;D&#x27;, &#x27;B&#x27;, &#x27;C&#x27;, &#x27;A&#x27;, &#x27;object&#x27;]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-53\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q53<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">53. What is the difference between instance methods, class methods and static methods?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><strong>Instance method:<\/strong> takes <code>self<\/code> and works with a specific object&#8217;s data.<\/li>\n<li><strong>Class method<\/strong> (<code>@classmethod<\/code>): takes <code>cls<\/code>, the class itself. Often used as an alternative constructor, like <code>from_string<\/code>.<\/li>\n<li><strong>Static method<\/strong> (<code>@staticmethod<\/code>): takes neither. It is a plain function that lives in the class because it logically belongs there.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class Date:\n    def __init__(self, day, month, year):\n        self.day, self.month, self.year = day, month, year\n\n    def display(self):                        # instance method\n        return f&quot;{self.day:02d}\/{self.month:02d}\/{self.year}&quot;\n\n    @classmethod\n    def from_string(cls, text):               # alternative constructor\n        d, m, y = map(int, text.split(&quot;-&quot;))\n        return cls(d, m, y)\n\n    @staticmethod\n    def is_leap(year):                        # utility\n        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n\nprint(Date.from_string(&quot;17-10-2026&quot;).display())\nprint(Date.is_leap(2028), Date.is_leap(1900))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n17\/10\/2026\nTrue False<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-54\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q54<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">54. What are magic (dunder) methods? Give examples.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Dunder (double underscore) methods let your classes work with Python&#8217;s built-in syntax and functions. For example, <code>__len__<\/code> makes <code>len(obj)<\/code> work, <code>__add__<\/code> defines <code>+<\/code>, and <code>__eq__<\/code> defines <code>==<\/code>.<\/p>\n<p><code>__str__<\/code> returns a readable string for end users (used by <code>print<\/code>), while <code>__repr__<\/code> returns an unambiguous developer-facing string, ideally one that could recreate the object (used in the REPL and in lists). If only <code>__repr__<\/code> is defined, <code>print<\/code> falls back to it.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class Vector:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __add__(self, other):\n        return Vector(self.x + other.x, self.y + other.y)\n    def __eq__(self, other):\n        return (self.x, self.y) == (other.x, other.y)\n    def __len__(self):\n        return 2\n    def __repr__(self):\n        return f&quot;Vector({self.x}, {self.y})&quot;\n    def __str__(self):\n        return f&quot;({self.x}, {self.y})&quot;\n\nv = Vector(1, 2) + Vector(3, 4)\nprint(v)\nprint([v])\nprint(v == Vector(4, 6), len(v))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n(4, 6)\n[Vector(4, 6)]\nTrue 2<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-55\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q55<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">55. How does encapsulation work in Python? What is name mangling?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Python has no true <code>private<\/code> keyword. It relies on conventions:<\/p>\n<ul><li><code>_name<\/code> (single underscore) means &#8220;internal, please do not touch&#8221;. It is not enforced.<\/li>\n<li><code>__name<\/code> (double underscore) triggers <strong>name mangling<\/strong>: Python renames it to <code>_ClassName__name<\/code>. This prevents accidental overriding in subclasses, but determined code can still reach it.<\/li><\/ul>\n<p>The Pythonic way to control access is with <code>@property<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class Wallet:\n    def __init__(self):\n        self._currency = &quot;INR&quot;\n        self.__balance = 500\n\n    def balance(self):\n        return self.__balance\n\nw = Wallet()\nprint(w._currency)\ntry:\n    print(w.__balance)\nexcept AttributeError as e:\n    print(&quot;AttributeError:&quot;, e)\nprint(w._Wallet__balance)    # name-mangled attribute\nprint(w.balance())<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nINR\nAttributeError: &#x27;Wallet&#x27; object has no attribute &#x27;__balance&#x27;\n500\n500<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-56\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q56<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">56. What is an abstract class in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>An abstract class defines methods that subclasses <strong>must<\/strong> implement, and cannot be instantiated itself. In Python you create one by inheriting from <code>ABC<\/code> and marking methods with <code>@abstractmethod<\/code>. If a subclass forgets to implement an abstract method, Python raises a <code>TypeError<\/code> when you try to create it. This enforces a common interface across many classes.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from abc import ABC, abstractmethod\n\nclass Shape(ABC):\n    @abstractmethod\n    def area(self):\n        ...\n\nclass Circle(Shape):\n    def __init__(self, r):\n        self.r = r\n    def area(self):\n        return round(3.14159 * self.r ** 2, 2)\n\nprint(Circle(3).area())\ntry:\n    Shape()\nexcept TypeError as e:\n    print(&quot;TypeError:&quot;, e)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n28.27\nTypeError: Can&#x27;t instantiate abstract class Shape without an implementation for abstract method &#x27;area&#x27;<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-57\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q57<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">57. What does the @property decorator do?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>@property<\/code> lets you access a method like an attribute, so you can add validation or computed values without changing how callers use the class. Combine it with <code>@name.setter<\/code> to control assignment. This is the Pythonic replacement for Java-style <code>get_x()<\/code> and <code>set_x()<\/code> methods.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class Product:\n    def __init__(self, name, price):\n        self.name = name\n        self.price = price          # goes through the setter\n\n    @property\n    def price(self):\n        return self._price\n\n    @price.setter\n    def price(self, value):\n        if value &lt; 0:\n            raise ValueError(&quot;Price cannot be negative&quot;)\n        self._price = value\n\n    @property\n    def price_with_gst(self):\n        return round(self._price * 1.18, 2)\n\np = Product(&quot;Keyboard&quot;, 1500)\nprint(p.price, p.price_with_gst)\ntry:\n    p.price = -10\nexcept ValueError as e:\n    print(&quot;ValueError:&quot;, e)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n1500 1770.0\nValueError: Price cannot be negative<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-58\" data-level=\"Intermediate\" data-topic=\"OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q58<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">OOP<\/span><\/div><h3 class=\"cd-q-title\">58. What is duck typing?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>&#8220;If it walks like a duck and quacks like a duck, it is a duck.&#8221; Python does not check an object&#8217;s type before calling a method. It only cares whether the object has the method you call. Any object with a <code>read()<\/code> method can be used where a file is expected, for example. This makes code flexible and is a form of polymorphism that does not need inheritance.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class PDFReport:\n    def export(self):\n        return &quot;Exported as PDF&quot;\n\nclass ExcelReport:\n    def export(self):\n        return &quot;Exported as Excel&quot;\n\ndef download(report):\n    print(report.export())     # no type check, only the method matters\n\ndownload(PDFReport())\ndownload(ExcelReport())<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nExported as PDF\nExported as Excel<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-59\" data-level=\"Intermediate\" data-topic=\"Exceptions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q59<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Exceptions<\/span><\/div><h3 class=\"cd-q-title\">59. How do you create and raise a custom exception?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Create a class that inherits from <code>Exception<\/code> (or a more specific built-in exception), then <code>raise<\/code> it. Custom exceptions make errors self-explanatory and let callers catch your specific errors separately. You can add extra attributes and use <code>raise ... from ...<\/code> to keep the original cause.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class InsufficientBalanceError(Exception):\n    def __init__(self, balance, amount):\n        self.balance = balance\n        self.amount = amount\n        super().__init__(f&quot;Need Rs {amount}, but balance is Rs {balance}&quot;)\n\ndef withdraw(balance, amount):\n    if amount &gt; balance:\n        raise InsufficientBalanceError(balance, amount)\n    return balance - amount\n\ntry:\n    withdraw(1000, 2500)\nexcept InsufficientBalanceError as e:\n    print(&quot;Error:&quot;, e)\n    print(&quot;Short by:&quot;, e.amount - e.balance)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nError: Need Rs 2500, but balance is Rs 1000\nShort by: 1500<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-60\" data-level=\"Intermediate\" data-topic=\"Context managers\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q60<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Context managers<\/span><\/div><h3 class=\"cd-q-title\">60. What is a context manager and how do you create one?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A context manager sets something up when a <code>with<\/code> block starts and guarantees clean-up when it ends, even if an exception is raised. Files, locks and database connections are typical examples. You can build one with a class that defines <code>__enter__<\/code> and <code>__exit__<\/code>, or more simply with the <code>@contextmanager<\/code> decorator from <code>contextlib<\/code>, where the code before <code>yield<\/code> is setup and the code after it is clean-up.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from contextlib import contextmanager\nimport time\n\nclass Timer:\n    def __enter__(self):\n        self.start = time.perf_counter()\n        return self\n    def __exit__(self, exc_type, exc, tb):\n        print(&quot;Block finished, exception:&quot;, exc_type)\n        return False   # do not suppress exceptions\n\n@contextmanager\ndef connection(name):\n    print(f&quot;Opening {name}&quot;)\n    try:\n        yield name.upper()\n    finally:\n        print(f&quot;Closing {name}&quot;)\n\nwith Timer():\n    sum(range(1000))\n\nwith connection(&quot;db&quot;) as conn:\n    print(&quot;Using&quot;, conn)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nBlock finished, exception: None\nOpening db\nUsing DB\nClosing db<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-61\" data-level=\"Intermediate\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q61<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">61. What is the difference between sort() and sorted()?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><code>list.sort()<\/code> sorts the list <strong>in place<\/strong> and returns <code>None<\/code>. It only exists on lists.<\/li>\n<li><code>sorted(iterable)<\/code> returns a <strong>new<\/strong> sorted list and works on any iterable, including tuples, strings and dicts.<\/li><\/ul>\n<p>Both accept <code>key<\/code> and <code>reverse<\/code>, and both use Timsort, which runs in O(n log n) and is <strong>stable<\/strong>: items that compare equal keep their original order. Stability lets you sort by several keys in steps.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>marks = [(&quot;Aman&quot;, 85), (&quot;Riya&quot;, 92), (&quot;Kabir&quot;, 85), (&quot;Sneha&quot;, 78)]\n\nby_marks = sorted(marks, key=lambda s: s[1], reverse=True)\nprint(by_marks)          # Aman stays before Kabir (stable)\n\nnums = [5, 2, 9]\nprint(nums.sort())       # returns None\nprint(nums)\nprint(sorted(&quot;python&quot;))\nprint(sorted(marks, key=lambda s: (-s[1], s[0])))   # marks desc, then name<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[(&#x27;Riya&#x27;, 92), (&#x27;Aman&#x27;, 85), (&#x27;Kabir&#x27;, 85), (&#x27;Sneha&#x27;, 78)]\nNone\n[2, 5, 9]\n[&#x27;h&#x27;, &#x27;n&#x27;, &#x27;o&#x27;, &#x27;p&#x27;, &#x27;t&#x27;, &#x27;y&#x27;]\n[(&#x27;Riya&#x27;, 92), (&#x27;Aman&#x27;, 85), (&#x27;Kabir&#x27;, 85), (&#x27;Sneha&#x27;, 78)]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-62\" data-level=\"Intermediate\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q62<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">62. How do get(), setdefault() and defaultdict help with dictionaries?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Accessing a missing key with <code>d[key]<\/code> raises a <code>KeyError<\/code>. Three ways to handle that:<\/p>\n<ul><li><code>d.get(key, default)<\/code> returns a default without changing the dict.<\/li>\n<li><code>d.setdefault(key, default)<\/code> returns the value, inserting the default first if the key is missing.<\/li>\n<li><code>collections.defaultdict(factory)<\/code> automatically creates a default value for any missing key, which is ideal for grouping.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from collections import defaultdict\n\nstock = {&quot;apple&quot;: 10}\nprint(stock.get(&quot;mango&quot;, 0))\n\ngroups = {}\ngroups.setdefault(&quot;A&quot;, []).append(&quot;Aman&quot;)\nprint(groups)\n\nby_branch = defaultdict(list)\nfor name, branch in [(&quot;Riya&quot;, &quot;CSE&quot;), (&quot;Kabir&quot;, &quot;ECE&quot;), (&quot;Sneha&quot;, &quot;CSE&quot;)]:\n    by_branch[branch].append(name)\nprint(dict(by_branch))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n0\n{&#x27;A&#x27;: [&#x27;Aman&#x27;]}\n{&#x27;CSE&#x27;: [&#x27;Riya&#x27;, &#x27;Sneha&#x27;], &#x27;ECE&#x27;: [&#x27;Kabir&#x27;]}<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-63\" data-level=\"Intermediate\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q63<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">63. What are namedtuple, deque and Counter in the collections module?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><code>namedtuple<\/code>: a tuple with named fields, so <code>p.x<\/code> is clearer than <code>p[0]<\/code>. Lightweight and immutable.<\/li>\n<li><code>deque<\/code>: a double-ended queue with O(1) appends and pops at both ends. A list is O(n) for <code>pop(0)<\/code>. Use it for queues and BFS.<\/li>\n<li><code>Counter<\/code>: counts hashable items, with <code>most_common()<\/code> and arithmetic between counters.<\/li>\n<li>Others worth knowing: <code>defaultdict<\/code>, <code>OrderedDict<\/code> and <code>ChainMap<\/code>.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from collections import namedtuple, deque, Counter\n\nPoint = namedtuple(&quot;Point&quot;, [&quot;x&quot;, &quot;y&quot;])\np = Point(3, 4)\nprint(p.x, p.y, p)\n\nqueue = deque([1, 2, 3])\nqueue.appendleft(0)\nqueue.append(4)\nprint(queue.popleft(), queue)\n\nprint(Counter(&quot;aabbbc&quot;) + Counter(&quot;abc&quot;))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n3 4 Point(x=3, y=4)\n0 deque([1, 2, 3, 4])\nCounter({&#x27;b&#x27;: 4, &#x27;a&#x27;: 3, &#x27;c&#x27;: 2})<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-64\" data-level=\"Intermediate\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q64<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">64. What is unpacking, and what is the walrus operator?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><strong>Unpacking<\/strong> assigns items of an iterable to several names in one line. A starred name collects &#8220;the rest&#8221; into a list. The <strong>walrus operator<\/strong> <code>:=<\/code> (Python 3.8+) assigns a value as part of an expression, which avoids computing something twice, for example inside a <code>while<\/code> condition or a comprehension.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>first, *middle, last = [10, 20, 30, 40, 50]\nprint(first, middle, last)\n\nname, (city, pin) = (&quot;Riya&quot;, (&quot;Pune&quot;, 411001))\nprint(name, city, pin)\n\ndata = [3, 8, 1, 9, 4]\nif (n := len(data)) &gt; 3:\n    print(f&quot;List is long ({n} items)&quot;)\n\nvalues = [y for x in data if (y := x * 10) &gt; 30]\nprint(values)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n10 [20, 30, 40] 50\nRiya Pune 411001\nList is long (5 items)\n[80, 90, 40]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-65\" data-level=\"Intermediate\" data-topic=\"Data types\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q65<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Data types<\/span><\/div><h3 class=\"cd-q-title\">65. What is a frozenset, and what makes an object hashable?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A <code>frozenset<\/code> is an immutable version of a set. Because it cannot change, it is hashable, so it can be a dictionary key or an element of another set, which a normal set cannot.<\/p>\n<p>An object is <strong>hashable<\/strong> if it has a hash value that never changes during its lifetime (<code>__hash__<\/code>) and can be compared with <code>__eq__<\/code>. Equal objects must have equal hashes. All immutable built-ins are hashable; tuples are hashable only if everything inside them is.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>skills = frozenset({&quot;python&quot;, &quot;sql&quot;})\nteams = {skills: &quot;Data team&quot;}\nprint(teams[frozenset({&quot;sql&quot;, &quot;python&quot;})])\n\nprint(hash((1, 2)) == hash((1, 2)))\ntry:\n    hash((1, [2, 3]))\nexcept TypeError as e:\n    print(&quot;TypeError:&quot;, e)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nData team\nTrue\nTypeError: unhashable type: &#x27;list&#x27;<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-66\" data-level=\"Intermediate\" data-topic=\"Strings\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q66<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Strings<\/span><\/div><h3 class=\"cd-q-title\">66. What are f-strings, and how do you format numbers with them?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>f-strings (Python 3.6+) embed expressions directly inside string literals: <code>f\"Hello {name}\"<\/code>. They are faster and more readable than <code>%<\/code> formatting or <code>str.format()<\/code>. A format specifier after a colon controls decimals, padding, alignment and separators. Adding <code>=<\/code> prints the expression too, which is handy for debugging.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>name, salary, score = &quot;Riya&quot;, 1250000.5, 0.8734\nprint(f&quot;{name} earns Rs {salary:,.2f}&quot;)\nprint(f&quot;Accuracy: {score:.1%}&quot;)\nprint(f&quot;|{name:&lt;8}|{name:&gt;8}|{name:^8}|&quot;)\nprint(f&quot;{42:05d} {255:x} {255:b}&quot;)\nx = 7\nprint(f&quot;{x * 6 = }&quot;)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nRiya earns Rs 1,250,000.50\nAccuracy: 87.3%\n|Riya    |    Riya|  Riya  |\n00042 ff 11111111\nx * 6 = 42<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-67\" data-level=\"Intermediate\" data-topic=\"Basics\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q67<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Basics<\/span><\/div><h3 class=\"cd-q-title\">67. What are type hints? Does Python enforce them?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Type hints (PEP 484) annotate the expected types of variables, parameters and return values, like <code>def area(r: float) -&gt; float<\/code>. Python does <strong>not<\/strong> enforce them at runtime: a wrong type still runs. Their value comes from tools: IDE autocompletion, and static checkers like mypy or Pyright that catch type errors before the code runs. Large codebases rely on them heavily.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def average(marks: list[float]) -&gt; float:\n    return sum(marks) \/ len(marks)\n\nprint(average([80, 90, 70]))\nprint(average.__annotations__)\n\ndef double(x: int) -&gt; int:\n    return x * 2\n\nprint(double(&quot;ab&quot;))   # a str is passed, Python runs it anyway<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n80.0\n{&#x27;marks&#x27;: list[float], &#x27;return&#x27;: &lt;class &#x27;float&#x27;&gt;}\nabab<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-68\" data-level=\"Intermediate\" data-topic=\"Files\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q68<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Files<\/span><\/div><h3 class=\"cd-q-title\">68. What is pickling and unpickling?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><strong>Pickling<\/strong> converts a Python object into a byte stream (serialisation) with <code>pickle.dump<\/code> or <code>pickle.dumps<\/code>, so it can be saved to disk or sent over a network. <strong>Unpickling<\/strong> rebuilds the object with <code>pickle.load<\/code> or <code>pickle.loads<\/code>. It handles almost any Python object, including custom classes, and is often used to save trained ML models.<\/p>\n<p>Never unpickle data from an untrusted source: a crafted pickle can execute arbitrary code. Use JSON for data exchange with other systems.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import pickle\n\nmodel_config = {&quot;model&quot;: &quot;logistic&quot;, &quot;C&quot;: 1.0, &quot;features&quot;: [&quot;age&quot;, &quot;income&quot;]}\nblob = pickle.dumps(model_config)\nprint(type(blob).__name__, len(blob), &quot;bytes&quot;)\n\nrestored = pickle.loads(blob)\nprint(restored == model_config, restored)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nbytes 78 bytes\nTrue {&#x27;model&#x27;: &#x27;logistic&#x27;, &#x27;C&#x27;: 1.0, &#x27;features&#x27;: [&#x27;age&#x27;, &#x27;income&#x27;]}<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-69\" data-level=\"Intermediate\" data-topic=\"Files\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q69<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Files<\/span><\/div><h3 class=\"cd-q-title\">69. How do you work with JSON in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The built-in <code>json<\/code> module converts between JSON text and Python objects. <code>json.dumps<\/code> turns an object into a JSON string and <code>json.loads<\/code> parses a string. <code>json.dump<\/code> and <code>json.load<\/code> do the same with files. JSON objects map to dicts, arrays to lists, <code>true<\/code>\/<code>false<\/code> to <code>True<\/code>\/<code>False<\/code>, and <code>null<\/code> to <code>None<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import json\n\napi_response = &#x27;{&quot;user&quot;: &quot;riya&quot;, &quot;active&quot;: true, &quot;skills&quot;: [&quot;python&quot;, &quot;sql&quot;], &quot;manager&quot;: null}&#x27;\ndata = json.loads(api_response)\nprint(data[&quot;skills&quot;], data[&quot;active&quot;], data[&quot;manager&quot;])\n\ndata[&quot;skills&quot;].append(&quot;pandas&quot;)\nprint(json.dumps(data, indent=2))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[&#x27;python&#x27;, &#x27;sql&#x27;] True None\n{\n  &quot;user&quot;: &quot;riya&quot;,\n  &quot;active&quot;: true,\n  &quot;skills&quot;: [\n    &quot;python&quot;,\n    &quot;sql&quot;,\n    &quot;pandas&quot;\n  ],\n  &quot;manager&quot;: null\n}<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-70\" data-level=\"Intermediate\" data-topic=\"Files\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q70<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Files<\/span><\/div><h3 class=\"cd-q-title\">70. How would you process a file that is too large to fit in memory?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Never call <code>read()<\/code> or <code>readlines()<\/code> on a huge file, because they load everything at once. Instead:<\/p>\n<ul><li>Iterate over the file object directly: it reads <strong>one line at a time<\/strong>.<\/li>\n<li>Wrap the processing in generators so each step handles one record at a time.<\/li>\n<li>For binary files, read fixed-size chunks with <code>f.read(chunk_size)<\/code>.<\/li>\n<li>For CSVs, use <code>pandas.read_csv(..., chunksize=100_000)<\/code>.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>with open(&quot;sales.log&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:\n    for i in range(1, 10001):\n        f.write(f&quot;order_{i},{i % 7 * 100}\\n&quot;)\n\ndef read_amounts(path):\n    with open(path, encoding=&quot;utf-8&quot;) as f:\n        for line in f:                    # one line in memory at a time\n            yield int(line.strip().split(&quot;,&quot;)[1])\n\ntotal = sum(read_amounts(&quot;sales.log&quot;))\nbig_orders = sum(1 for amt in read_amounts(&quot;sales.log&quot;) if amt &gt;= 500)\nprint(total, big_orders)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n2999800 2856<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-71\" data-level=\"Intermediate\" data-topic=\"Modules\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q71<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Modules<\/span><\/div><h3 class=\"cd-q-title\">71. What is a virtual environment, and why should you use one?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A virtual environment is an isolated folder with its own Python interpreter and installed packages. Each project gets its own versions of libraries, so project A can use Django 4 while project B uses Django 5 without conflicts, and you never pollute the system Python.<\/p>\n<p>Typical workflow:<\/p>\n<ul><li><code>python -m venv .venv<\/code> to create it.<\/li>\n<li><code>source .venv\/bin\/activate<\/code> on Linux and macOS, or <code>.venv\\Scripts\\activate<\/code> on Windows.<\/li>\n<li><code>pip install -r requirements.txt<\/code> to install dependencies.<\/li>\n<li><code>pip freeze &gt; requirements.txt<\/code> to record exact versions.<\/li><\/ul>\n<p>Tools like <code>poetry<\/code>, <code>pipenv<\/code>, <code>conda<\/code> and <code>uv<\/code> build on the same idea.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import sys\nprint(&quot;Running inside a venv:&quot;, sys.prefix != sys.base_prefix)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nRunning inside a venv: False<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-72\" data-level=\"Intermediate\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q72<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">72. Two Sum: find two numbers in a list that add up to a target.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The brute-force approach checks every pair in O(n\u00b2). The optimal approach uses a dictionary that maps each number to its index. For each number, check whether <code>target - number<\/code> has already been seen. That gives O(n) time and O(n) space, and it is one of the most asked coding questions in Python interviews. Our <a href=\"https:\/\/codeanddebug.in\/blog\/two-sum-leetcode-1\/\">Two Sum (LeetCode 1)<\/a> post walks through it step by step.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def two_sum(nums, target):\n    seen = {}\n    for i, num in enumerate(nums):\n        need = target - num\n        if need in seen:\n            return [seen[need], i]\n        seen[num] = i\n    return []\n\nprint(two_sum([2, 7, 11, 15], 9))\nprint(two_sum([3, 2, 4], 6))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[0, 1]\n[1, 2]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-73\" data-level=\"Intermediate\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q73<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">73. Check whether two strings are anagrams.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Two strings are anagrams if they contain the same characters with the same counts, like &#8220;listen&#8221; and &#8220;silent&#8221;. Sorting both strings works in O(n log n). Comparing two <code>Counter<\/code> objects works in O(n). See our <a href=\"https:\/\/codeanddebug.in\/blog\/valid-anagram\/\">Valid Anagram<\/a> walkthrough for more approaches.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from collections import Counter\n\ndef is_anagram(a, b):\n    return Counter(a) == Counter(b)\n\ndef is_anagram_sorted(a, b):\n    return sorted(a) == sorted(b)\n\nprint(is_anagram(&quot;listen&quot;, &quot;silent&quot;), is_anagram(&quot;rat&quot;, &quot;car&quot;))\nprint(is_anagram_sorted(&quot;dusty&quot;, &quot;study&quot;))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nTrue False\nTrue<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-74\" data-level=\"Intermediate\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q74<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">74. Flatten a nested list of any depth.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Recursion fits naturally: walk through each item, and if it is a list, flatten it too, otherwise yield it. A generator with <code>yield from<\/code> keeps the code short and memory-friendly. Interviewers may follow up by asking for an iterative version using a stack, which avoids Python&#8217;s recursion limit on very deep nesting.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def flatten(items):\n    for item in items:\n        if isinstance(item, list):\n            yield from flatten(item)\n        else:\n            yield item\n\nnested = [1, [2, [3, [4, 5]], 6], [[7]], 8]\nprint(list(flatten(nested)))\n\ndef flatten_iterative(items):\n    stack, result = [items], []\n    while stack:\n        current = stack.pop()\n        if isinstance(current, list):\n            stack.extend(reversed(current))\n        else:\n            result.append(current)\n    return result\n\nprint(flatten_iterative(nested))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[1, 2, 3, 4, 5, 6, 7, 8]\n[1, 2, 3, 4, 5, 6, 7, 8]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-75\" data-level=\"Intermediate\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q75<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">75. Find the missing number in a list containing 0 to n.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The list has n distinct numbers taken from 0 to n, so exactly one is missing. The sum of 0 to n is n(n+1)\/2, so the missing number is that total minus the actual sum: O(n) time and O(1) space. The XOR trick avoids any risk of overflow in other languages. We solve this step by step in our <a href=\"https:\/\/codeanddebug.in\/blog\/find-the-missing-number\/\">Missing Number (LeetCode 268)<\/a> post.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def missing_number(nums):\n    n = len(nums)\n    return n * (n + 1) \/\/ 2 - sum(nums)\n\ndef missing_number_xor(nums):\n    result = len(nums)\n    for i, num in enumerate(nums):\n        result ^= i ^ num\n    return result\n\nprint(missing_number([3, 0, 1]))\nprint(missing_number_xor([9, 6, 4, 2, 3, 5, 7, 0, 1]))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n2\n8<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"python-interview-questions-for-experienced\">Advanced Python interview questions for experienced developers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These 25 questions are aimed at candidates with 2 or more years of experience. They test how well you understand what happens under the hood: the GIL and concurrency, memory management, metaclasses and descriptors, performance, testing, modern Python features, and NumPy and Pandas for data roles.<\/p>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-76\" data-level=\"Experienced\" data-topic=\"Concurrency\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q76<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Concurrency<\/span><\/div><h3 class=\"cd-q-title\">76. What is the GIL (Global Interpreter Lock)?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The GIL is a lock in CPython that allows only <strong>one thread to execute Python bytecode at a time<\/strong>, even on a multi-core machine. It exists because CPython&#8217;s memory management (reference counting) is not thread-safe, and a single lock was a simple, fast way to protect it.<\/p>\n<ul><li>For <strong>I\/O-bound<\/strong> work (network calls, file and database access), threads still help, because a thread releases the GIL while it waits.<\/li>\n<li>For <strong>CPU-bound<\/strong> work (heavy calculations), threads do not run in parallel, so use <code>multiprocessing<\/code>, or libraries like NumPy that do the work in C and release the GIL.<\/li><\/ul>\n<p>Python 3.13 introduced an experimental &#8220;free-threaded&#8221; build (PEP 703) that can run without the GIL. It is optional and not yet the default, so the standard answer still applies to most production code.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import sys\nprint(sys.version.split()[0])\ncheck = getattr(sys, &quot;_is_gil_enabled&quot;, None)\nprint(&quot;GIL enabled:&quot;, check() if check else True)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n3.13.16\nGIL enabled: True<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-77\" data-level=\"Experienced\" data-topic=\"Concurrency\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q77<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Concurrency<\/span><\/div><h3 class=\"cd-q-title\">77. When would you use threading, multiprocessing or asyncio?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><strong>threading:<\/strong> I\/O-bound tasks with a moderate number of concurrent operations, like downloading 20 files. Threads share memory, so protect shared data with locks.<\/li>\n<li><strong>multiprocessing:<\/strong> CPU-bound tasks, like processing images or crunching numbers. Each process has its own interpreter and its own GIL, so work truly runs in parallel on several cores. The cost is higher memory use and data must be pickled to move between processes.<\/li>\n<li><strong>asyncio:<\/strong> very large numbers of I\/O-bound tasks, like thousands of network requests or websocket connections, in a single thread with an event loop. Requires async-aware libraries (aiohttp, asyncpg).<\/li><\/ul>\n<p><code>concurrent.futures<\/code> gives the same simple API (<code>ThreadPoolExecutor<\/code>, <code>ProcessPoolExecutor<\/code>) for the first two.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from concurrent.futures import ThreadPoolExecutor\nimport time\n\ndef fake_download(n):\n    time.sleep(0.2)          # simulates waiting on the network\n    return f&quot;file_{n} done&quot;\n\nstart = time.perf_counter()\nwith ThreadPoolExecutor(max_workers=5) as pool:\n    results = list(pool.map(fake_download, range(5)))\nelapsed = time.perf_counter() - start\nprint(results)\nprint(&quot;5 downloads finished in under 0.5 s:&quot;, elapsed &lt; 0.5)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[&#x27;file_0 done&#x27;, &#x27;file_1 done&#x27;, &#x27;file_2 done&#x27;, &#x27;file_3 done&#x27;, &#x27;file_4 done&#x27;]\n5 downloads finished in under 0.5 s: True<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-78\" data-level=\"Experienced\" data-topic=\"Concurrency\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q78<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Concurrency<\/span><\/div><h3 class=\"cd-q-title\">78. How does async and await work? Give an example.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>async def<\/code> defines a <strong>coroutine<\/strong>. Calling it creates a coroutine object, and nothing runs until it is awaited or scheduled on the event loop. <code>await<\/code> pauses the current coroutine until the awaited operation finishes, and while it waits, the event loop runs other coroutines. <code>asyncio.gather<\/code> runs several coroutines concurrently and returns their results in the order you passed them, not the order they finish.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import asyncio\n\nasync def fetch(name, delay):\n    print(f&quot;start {name}&quot;)\n    await asyncio.sleep(delay)      # non-blocking wait\n    print(f&quot;end {name}&quot;)\n    return f&quot;{name}:{delay}s&quot;\n\nasync def main():\n    results = await asyncio.gather(\n        fetch(&quot;users&quot;, 0.3), fetch(&quot;orders&quot;, 0.1), fetch(&quot;stock&quot;, 0.2))\n    print(results)\n\nasyncio.run(main())<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nstart users\nstart orders\nstart stock\nend orders\nend stock\nend users\n[&#x27;users:0.3s&#x27;, &#x27;orders:0.1s&#x27;, &#x27;stock:0.2s&#x27;]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-79\" data-level=\"Experienced\" data-topic=\"Concurrency\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q79<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Concurrency<\/span><\/div><h3 class=\"cd-q-title\">79. What is a race condition and how do you prevent it in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A race condition happens when several threads read and modify shared data at the same time, and the result depends on unpredictable timing. Even <code>counter += 1<\/code> is not atomic: it is a read, an add and a write, and a thread switch can happen between them. Protect shared state with a <code>threading.Lock<\/code>, ideally used as a context manager, or avoid shared state entirely by using a <code>queue.Queue<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import threading\n\nbalance = 0\nlock = threading.Lock()\n\ndef deposit_many(times):\n    global balance\n    for _ in range(times):\n        with lock:              # only one thread updates at a time\n            balance += 1\n\nthreads = [threading.Thread(target=deposit_many, args=(100_000,)) for _ in range(4)]\nfor t in threads: t.start()\nfor t in threads: t.join()\nprint(&quot;Final balance:&quot;, balance)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nFinal balance: 400000<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-80\" data-level=\"Experienced\" data-topic=\"Memory\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q80<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Memory<\/span><\/div><h3 class=\"cd-q-title\">80. How does Python&#x27;s garbage collector handle reference cycles?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Reference counting frees an object as soon as nothing refers to it, but two objects that refer to each other keep each other&#8217;s count above zero forever. CPython&#8217;s <strong>generational garbage collector<\/strong> (the <code>gc<\/code> module) periodically scans container objects, finds groups that are only reachable from each other, and frees them. Objects are grouped into generations: new objects are checked often, and objects that survive several collections are checked less often, since they tend to live long.<\/p>\n<p>To avoid creating cycles in the first place, for example parent-child links or caches, use the <code>weakref<\/code> module.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import gc\n\nclass Node:\n    def __init__(self, name):\n        self.name = name\n        self.partner = None\n\ngc.collect()\na, b = Node(&quot;a&quot;), Node(&quot;b&quot;)\na.partner, b.partner = b, a      # reference cycle\ndel a, b                         # refcounts never reach zero\nprint(&quot;Unreachable objects found:&quot;, gc.collect() &gt; 0)\nprint(&quot;Thresholds:&quot;, gc.get_threshold())<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nUnreachable objects found: True\nThresholds: (2000, 10, 10)<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-81\" data-level=\"Experienced\" data-topic=\"Memory\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q81<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Memory<\/span><\/div><h3 class=\"cd-q-title\">81. What are __slots__ and when should you use them?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>By default every instance stores its attributes in a per-object <code>__dict__<\/code>, which is flexible but costs memory. Declaring <code>__slots__ = (\"x\", \"y\")<\/code> tells Python to reserve fixed space for exactly those attributes and skip the <code>__dict__<\/code>. Instances use noticeably less memory and attribute access is slightly faster. The trade-off is that you cannot add new attributes dynamically. Use it when you create millions of small objects. <code>@dataclass(slots=True)<\/code> does this for you in Python 3.10+.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import sys\n\nclass PointDict:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n\nclass PointSlots:\n    __slots__ = (&quot;x&quot;, &quot;y&quot;)\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n\na, b = PointDict(1, 2), PointSlots(1, 2)\nprint(&quot;with __dict__:&quot;, sys.getsizeof(a) + sys.getsizeof(a.__dict__), &quot;bytes&quot;)\nprint(&quot;with __slots__:&quot;, sys.getsizeof(b), &quot;bytes&quot;)\ntry:\n    b.z = 3\nexcept AttributeError as e:\n    print(&quot;AttributeError:&quot;, e)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nwith __dict__: 344 bytes\nwith __slots__: 48 bytes\nAttributeError: &#x27;PointSlots&#x27; object has no attribute &#x27;z&#x27; and no __dict__ for setting new attributes<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-82\" data-level=\"Experienced\" data-topic=\"Advanced OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q82<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Advanced OOP<\/span><\/div><h3 class=\"cd-q-title\">82. What is a metaclass?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>In Python, classes are objects too, and a metaclass is the &#8220;class of a class&#8221;: it controls how classes are created. The default metaclass is <code>type<\/code>. A custom metaclass (inheriting from <code>type<\/code> and overriding <code>__new__<\/code> or <code>__init__<\/code>) can automatically register classes, enforce naming rules, or add methods. Django models and SQLAlchemy use metaclasses internally.<\/p>\n<p>They are powerful but rarely needed in application code. Class decorators and <code>__init_subclass__<\/code> usually solve the same problems more simply, and saying so is a good interview answer.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class PluginRegistry(type):\n    plugins = {}\n    def __new__(mcs, name, bases, namespace):\n        cls = super().__new__(mcs, name, bases, namespace)\n        if bases:                       # skip the base class itself\n            mcs.plugins[name.lower()] = cls\n        return cls\n\nclass Plugin(metaclass=PluginRegistry):\n    pass\n\nclass CsvExporter(Plugin): pass\nclass PdfExporter(Plugin): pass\n\nprint(type(Plugin))\nprint(list(PluginRegistry.plugins))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n&lt;class &#x27;__main__.PluginRegistry&#x27;&gt;\n[&#x27;csvexporter&#x27;, &#x27;pdfexporter&#x27;]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-83\" data-level=\"Experienced\" data-topic=\"Advanced OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q83<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Advanced OOP<\/span><\/div><h3 class=\"cd-q-title\">83. What is a descriptor?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A descriptor is an object that defines <code>__get__<\/code>, <code>__set__<\/code> or <code>__delete__<\/code> and is stored as a class attribute. When you access that attribute on an instance, Python calls the descriptor&#8217;s methods instead of reading a plain value. Descriptors are the machinery behind <code>@property<\/code>, <code>@classmethod<\/code>, <code>@staticmethod<\/code> and ORM fields. They are useful for reusable validation across many attributes.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>class Positive:\n    def __set_name__(self, owner, name):\n        self.name = &quot;_&quot; + name\n    def __get__(self, obj, objtype=None):\n        return getattr(obj, self.name)\n    def __set__(self, obj, value):\n        if value &lt;= 0:\n            raise ValueError(f&quot;{self.name[1:]} must be positive&quot;)\n        setattr(obj, self.name, value)\n\nclass Order:\n    quantity = Positive()\n    price = Positive()\n    def __init__(self, quantity, price):\n        self.quantity, self.price = quantity, price\n\no = Order(3, 499)\nprint(o.quantity * o.price)\ntry:\n    o.price = -5\nexcept ValueError as e:\n    print(&quot;ValueError:&quot;, e)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n1497\nValueError: price must be positive<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-84\" data-level=\"Experienced\" data-topic=\"Performance\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q84<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Performance<\/span><\/div><h3 class=\"cd-q-title\">84. How are Python dictionaries implemented internally?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A dict is a <strong>hash table<\/strong>. When you insert a key, Python computes <code>hash(key)<\/code>, uses it to pick a slot, and stores the key, value and hash there. On a collision (two keys mapping to the same slot), CPython uses <strong>open addressing<\/strong>: it probes other slots in a pseudo-random sequence until it finds a free one. When the table gets about two-thirds full, it is resized to keep lookups fast.<\/p>\n<p>Since Python 3.6, CPython stores entries in a compact array in insertion order, with a separate sparse index table pointing into it. That saves memory and is why dicts preserve insertion order (guaranteed from 3.7). Average lookup, insert and delete are O(1). The worst case is O(n) if many keys collide.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>print(hash(&quot;python&quot;) == hash(&quot;python&quot;))\nprint(hash(42), hash(True), hash(1.0) == hash(1))\nd = {1: &quot;int&quot;, True: &quot;bool&quot;}     # 1 == True and same hash, so same key\nprint(d)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nTrue\n42 1 True\n{1: &#x27;bool&#x27;}<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-85\" data-level=\"Experienced\" data-topic=\"Performance\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q85<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Performance<\/span><\/div><h3 class=\"cd-q-title\">85. What is the time complexity of common list, dict and set operations?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Knowing these is essential for writing efficient code and for coding interviews. For the basics of Big O, see our <a href=\"https:\/\/codeanddebug.in\/blog\/time-complexity-and-space-complexity\/\">time and space complexity guide<\/a>.<\/p>\n<table><thead><tr><th>Operation<\/th><th>list<\/th><th>dict \/ set<\/th><\/tr><\/thead><tbody>\n<tr><td>Access by index or key<\/td><td>O(1)<\/td><td>O(1) average<\/td><\/tr>\n<tr><td>Membership test (<code>x in c<\/code>)<\/td><td>O(n)<\/td><td>O(1) average<\/td><\/tr>\n<tr><td>Append \/ add<\/td><td>O(1) amortised<\/td><td>O(1) average<\/td><\/tr>\n<tr><td>Insert or delete at the start<\/td><td>O(n)<\/td><td>n\/a<\/td><\/tr>\n<tr><td>Pop from the end<\/td><td>O(1)<\/td><td>n\/a<\/td><\/tr>\n<tr><td>Delete by key<\/td><td>n\/a<\/td><td>O(1) average<\/td><\/tr>\n<tr><td>Sort<\/td><td>O(n log n)<\/td><td>n\/a<\/td><\/tr>\n<tr><td>Iterate<\/td><td>O(n)<\/td><td>O(n)<\/td><\/tr><\/tbody><\/table>\n<p>The classic interview follow-up: if you check <code>x in my_list<\/code> inside a loop, convert the list to a set first.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import timeit\ndata_list = list(range(100_000))\ndata_set = set(data_list)\nt_list = timeit.timeit(lambda: 99_999 in data_list, number=200)\nt_set = timeit.timeit(lambda: 99_999 in data_set, number=200)\nprint(&quot;set lookup is faster:&quot;, t_set &lt; t_list)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nset lookup is faster: True<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-86\" data-level=\"Experienced\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q86<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">86. What is the late binding closure problem?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Closures look up variables when the inner function is <strong>called<\/strong>, not when it is created. So functions created in a loop all see the loop variable&#8217;s final value. This trips up even experienced developers. Fix it by binding the current value as a default argument, or by using <code>functools.partial<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>multipliers = [lambda x: x * i for i in range(1, 4)]\nprint([f(10) for f in multipliers])          # all use i = 3\n\nfixed = [lambda x, i=i: x * i for i in range(1, 4)]\nprint([f(10) for f in fixed])<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[30, 30, 30]\n[10, 20, 30]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-87\" data-level=\"Experienced\" data-topic=\"Memory\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q87<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Memory<\/span><\/div><h3 class=\"cd-q-title\">87. What is integer caching and string interning?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>CPython pre-creates and reuses integer objects from <strong>-5 to 256<\/strong>, so any two variables holding, say, 100 point to the same object. Larger integers created at runtime are usually separate objects. Similarly, short strings that look like identifiers are often <strong>interned<\/strong> (stored once and reused), and you can force it with <code>sys.intern<\/code>.<\/p>\n<p>These are implementation details. The lesson for interviews: never use <code>is<\/code> to compare numbers or strings. Use <code>==<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>a = int(&quot;256&quot;); b = int(&quot;256&quot;)\nprint(a is b)       # cached small integer\nc = int(&quot;257&quot;); d = int(&quot;257&quot;)\nprint(c is d)       # separate objects\nprint(c == d)       # always compare values with ==\n\nimport sys\ns1 = sys.intern(&quot;code and debug&quot;)\ns2 = sys.intern(&quot;code and debug&quot;)\nprint(s1 is s2)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nTrue\nFalse\nTrue\nTrue<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-88\" data-level=\"Experienced\" data-topic=\"Performance\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q88<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Performance<\/span><\/div><h3 class=\"cd-q-title\">88. What does functools.lru_cache do?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>@lru_cache<\/code> memoises a function: it stores results for arguments it has already seen and returns the cached result instead of recomputing. LRU means Least Recently Used: when the cache is full (<code>maxsize<\/code>), the oldest unused entries are dropped. <code>@cache<\/code> (Python 3.9+) is the unbounded version. The arguments must be hashable. It turns the naive recursive Fibonacci from exponential time into linear time.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fib(n):\n    return n if n &lt; 2 else fib(n - 1) + fib(n - 2)\n\nprint(fib(100))\nprint(fib.cache_info())<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n354224848179261915075\nCacheInfo(hits=98, misses=101, maxsize=None, currsize=101)<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-89\" data-level=\"Experienced\" data-topic=\"Performance\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q89<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Performance<\/span><\/div><h3 class=\"cd-q-title\">89. Name some useful functions from the itertools module.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>itertools<\/code> provides fast, memory-efficient building blocks that return iterators:<\/p>\n<ul><li><code>chain<\/code>: join several iterables end to end.<\/li>\n<li><code>islice<\/code>: slice any iterator, even an infinite one.<\/li>\n<li><code>groupby<\/code>: group consecutive items with the same key. Sort by that key first.<\/li>\n<li><code>combinations<\/code>, <code>permutations<\/code>, <code>product<\/code>: combinatorics without nested loops.<\/li>\n<li><code>accumulate<\/code>: running totals.<\/li>\n<li><code>count<\/code>, <code>cycle<\/code>, <code>repeat<\/code>: infinite iterators.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from itertools import chain, groupby, combinations, accumulate, islice, count\n\nprint(list(chain([1, 2], (3, 4), &quot;ab&quot;)))\nprint(list(combinations(&quot;ABC&quot;, 2)))\nprint(list(accumulate([100, 200, 50])))\nprint(list(islice(count(10, 5), 4)))\n\nsales = [(&quot;Pune&quot;, 300), (&quot;Pune&quot;, 200), (&quot;Surat&quot;, 150)]\nfor city, rows in groupby(sales, key=lambda r: r[0]):\n    print(city, sum(amount for _, amount in rows))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[1, 2, 3, 4, &#x27;a&#x27;, &#x27;b&#x27;]\n[(&#x27;A&#x27;, &#x27;B&#x27;), (&#x27;A&#x27;, &#x27;C&#x27;), (&#x27;B&#x27;, &#x27;C&#x27;)]\n[100, 300, 350]\n[10, 15, 20, 25]\nPune 500\nSurat 150<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-90\" data-level=\"Experienced\" data-topic=\"Advanced OOP\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q90<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Advanced OOP<\/span><\/div><h3 class=\"cd-q-title\">90. What are dataclasses?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The <code>@dataclass<\/code> decorator (Python 3.7+) generates <code>__init__<\/code>, <code>__repr__<\/code> and <code>__eq__<\/code> automatically from the class&#8217;s type-annotated fields, which removes a lot of boilerplate for classes that mainly hold data. Options include <code>frozen=True<\/code> for immutable, hashable instances, <code>order=True<\/code> to generate comparison methods, and <code>slots=True<\/code> for lower memory use. Use <code>field(default_factory=list)<\/code> for mutable defaults.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from dataclasses import dataclass, field\n\n@dataclass(order=True)\nclass Student:\n    cgpa: float\n    name: str\n    skills: list = field(default_factory=list)\n\na = Student(8.7, &quot;Riya&quot;, [&quot;python&quot;])\nb = Student(9.1, &quot;Kabir&quot;)\nprint(a)\nprint(a == Student(8.7, &quot;Riya&quot;, [&quot;python&quot;]))\nprint(max(a, b).name)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nStudent(cgpa=8.7, name=&#x27;Riya&#x27;, skills=[&#x27;python&#x27;])\nTrue\nKabir<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-91\" data-level=\"Experienced\" data-topic=\"Iterators &amp; generators\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q91<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Iterators &amp; generators<\/span><\/div><h3 class=\"cd-q-title\">91. What do send() and yield from do in generators?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>yield from iterable<\/code> delegates to another generator or iterable, yielding all of its values, which makes it easy to compose generators. <code>send(value)<\/code> resumes a paused generator and makes the current <code>yield<\/code> expression evaluate to <code>value<\/code>, so data flows <em>into<\/em> the generator. This two-way communication is what Python&#8217;s coroutines were originally built on. Prime a generator with <code>next()<\/code> before the first <code>send()<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def running_average():\n    total, count, average = 0, 0, None\n    while True:\n        value = yield average\n        total += value\n        count += 1\n        average = total \/ count\n\navg = running_average()\nnext(avg)                    # prime the generator\nfor mark in [80, 90, 70]:\n    print(avg.send(mark))\n\ndef all_items():\n    yield from [&quot;a&quot;, &quot;b&quot;]\n    yield from range(3)\n\nprint(list(all_items()))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n80.0\n85.0\n80.0\n[&#x27;a&#x27;, &#x27;b&#x27;, 0, 1, 2]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-92\" data-level=\"Experienced\" data-topic=\"Modern Python\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q92<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Modern Python<\/span><\/div><h3 class=\"cd-q-title\">92. What is structural pattern matching (match-case)?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Introduced in Python 3.10, <code>match<\/code> compares a value against <strong>patterns<\/strong>, not just equal values. It can unpack sequences and dictionaries, check types, bind variables and add <code>if<\/code> guards, which makes parsers, command handlers and API response handling much cleaner than long <code>if\/elif<\/code> chains. The underscore <code>_<\/code> is the wildcard that matches anything.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def handle(event):\n    match event:\n        case {&quot;type&quot;: &quot;click&quot;, &quot;x&quot;: x, &quot;y&quot;: y}:\n            return f&quot;Click at ({x}, {y})&quot;\n        case {&quot;type&quot;: &quot;key&quot;, &quot;key&quot;: &quot;q&quot; | &quot;Q&quot;}:\n            return &quot;Quit&quot;\n        case [first, *rest]:\n            return f&quot;List starting with {first}, {len(rest)} more&quot;\n        case int(n) if n &lt; 0:\n            return &quot;Negative number&quot;\n        case _:\n            return &quot;Unknown event&quot;\n\nprint(handle({&quot;type&quot;: &quot;click&quot;, &quot;x&quot;: 10, &quot;y&quot;: 20}))\nprint(handle({&quot;type&quot;: &quot;key&quot;, &quot;key&quot;: &quot;Q&quot;}))\nprint(handle([5, 6, 7]))\nprint(handle(-3), &quot;|&quot;, handle(3.5))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nClick at (10, 20)\nQuit\nList starting with 5, 2 more\nNegative number | Unknown event<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-93\" data-level=\"Experienced\" data-topic=\"Modern Python\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q93<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Modern Python<\/span><\/div><h3 class=\"cd-q-title\">93. What are some important features added in recent Python versions?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><ul><li><strong>3.8:<\/strong> walrus operator <code>:=<\/code>, positional-only parameters with <code>\/<\/code>, and <code>f\"{x=}\"<\/code> debugging.<\/li>\n<li><strong>3.9:<\/strong> dict merge operators <code>|<\/code> and <code>|=<\/code>, built-in generics like <code>list[int]<\/code>, and <code>str.removeprefix()<\/code>.<\/li>\n<li><strong>3.10:<\/strong> structural pattern matching (<code>match<\/code>), the <code>X | Y<\/code> union type syntax, and clearer error messages.<\/li>\n<li><strong>3.11:<\/strong> large interpreter speed-ups, exception groups with <code>except*<\/code>, and <code>tomllib<\/code>.<\/li>\n<li><strong>3.12:<\/strong> new type parameter syntax (<code>def first[T](items: list[T]) -&gt; T<\/code>), the <code>type<\/code> statement, and more flexible f-strings.<\/li>\n<li><strong>3.13:<\/strong> a new interactive REPL, an experimental free-threaded build without the GIL, and an experimental JIT compiler.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>defaults = {&quot;theme&quot;: &quot;light&quot;, &quot;lang&quot;: &quot;en&quot;}\nuser = {&quot;theme&quot;: &quot;dark&quot;}\nprint(defaults | user)                      # 3.9 dict merge\n\ndef first[T](items: list[T]) -&gt; T:          # 3.12 generics syntax\n    return items[0]\nprint(first([&quot;python&quot;, &quot;sql&quot;]))\n\nprint(&quot;report_final.pdf&quot;.removeprefix(&quot;report_&quot;))\nvalue = 42\nprint(f&quot;{value = }&quot;)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n{&#x27;theme&#x27;: &#x27;dark&#x27;, &#x27;lang&#x27;: &#x27;en&#x27;}\npython\nfinal.pdf\nvalue = 42<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-94\" data-level=\"Experienced\" data-topic=\"Testing\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q94<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Testing<\/span><\/div><h3 class=\"cd-q-title\">94. How do you write unit tests in Python?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>The two main options are the built-in <code>unittest<\/code> module and the third-party <strong>pytest<\/strong>, which most teams prefer because tests are plain functions with plain <code>assert<\/code> statements, and it has powerful fixtures and parametrisation. A good test is fast, independent, and checks one behaviour, including edge cases and expected errors. Use <code>unittest.mock<\/code> to replace external dependencies.<\/p>\n<p>With pytest you would write <code>def test_discount(): assert apply_discount(1000, 10) == 900<\/code> in a file named <code>test_*.py<\/code> and run <code>pytest<\/code>. The same idea with <code>unittest<\/code>:<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import unittest\n\ndef apply_discount(price, percent):\n    if not 0 &lt;= percent &lt;= 100:\n        raise ValueError(&quot;percent must be between 0 and 100&quot;)\n    return price * (100 - percent) \/ 100\n\nclass TestDiscount(unittest.TestCase):\n    def test_normal(self):\n        self.assertEqual(apply_discount(1000, 10), 900)\n    def test_zero(self):\n        self.assertEqual(apply_discount(500, 0), 500)\n    def test_invalid(self):\n        with self.assertRaises(ValueError):\n            apply_discount(500, 120)\n\nsuite = unittest.defaultTestLoader.loadTestsFromTestCase(TestDiscount)\nresult = unittest.TextTestRunner(verbosity=0).run(suite)\nprint(&quot;Tests run:&quot;, result.testsRun, &quot;| Failures:&quot;, len(result.failures))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nTests run: 3 | Failures: 0\n----------------------------------------------------------------------\nRan 3 tests in 0.000s\n\nOK<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-95\" data-level=\"Experienced\" data-topic=\"Performance\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q95<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Performance<\/span><\/div><h3 class=\"cd-q-title\">95. How do you find and fix slow Python code?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Measure first, then optimise. Guessing usually targets the wrong code.<\/p>\n<ol><li><strong>Profile:<\/strong> <code>python -m cProfile -s cumtime app.py<\/code> shows which functions take the most time. <code>line_profiler<\/code> goes line by line, and <code>tracemalloc<\/code> tracks memory.<\/li>\n<li><strong>Benchmark<\/strong> small alternatives with <code>timeit<\/code>.<\/li>\n<li><strong>Fix the algorithm first:<\/strong> a set instead of a list for lookups, or avoiding nested loops, beats any micro-optimisation.<\/li>\n<li><strong>Use built-ins and libraries:<\/strong> <code>sum<\/code>, <code>sorted<\/code>, comprehensions and NumPy run in C.<\/li>\n<li><strong>Cache<\/strong> repeated work with <code>lru_cache<\/code>.<\/li>\n<li><strong>Go parallel<\/strong> with multiprocessing for CPU-bound work, or use PyPy, Cython or Numba for hot loops.<\/li><\/ol><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import cProfile, pstats, io\n\ndef slow_unique(items):\n    result = []\n    for x in items:\n        if x not in result:      # O(n) check inside a loop: O(n^2) total\n            result.append(x)\n    return result\n\nprofiler = cProfile.Profile()\nprofiler.enable()\nslow_unique(list(range(3000)) * 2)\nprofiler.disable()\n\nstats = pstats.Stats(profiler, stream=io.StringIO()).sort_stats(&quot;tottime&quot;)\ntop = stats.fcn_list[0]\nprint(&quot;Function using the most time:&quot;, top[2])<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\nFunction using the most time: slow_unique<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-96\" data-level=\"Experienced\" data-topic=\"Functions\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q96<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Functions<\/span><\/div><h3 class=\"cd-q-title\">96. Is Python pass-by-value or pass-by-reference?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>Neither, exactly. Python uses <strong>pass-by-object-reference<\/strong> (also called call-by-sharing). The function receives a reference to the same object the caller passed. What happens next depends on mutability:<\/p>\n<ul><li>If you <strong>mutate<\/strong> a mutable object (append to a list), the caller sees the change.<\/li>\n<li>If you <strong>rebind<\/strong> the parameter to a new object (<code>x = x + 1<\/code> or <code>lst = [...]<\/code>), only the local name changes, and the caller&#8217;s variable is unaffected.<\/li><\/ul><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>def modify(nums, count):\n    nums.append(4)       # mutates the caller&#x27;s list\n    count += 1           # rebinds a local name only\n    nums = [0]           # rebinds, caller unaffected\n\nmy_list, my_count = [1, 2, 3], 10\nmodify(my_list, my_count)\nprint(my_list, my_count)<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[1, 2, 3, 4] 10<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-97\" data-level=\"Experienced\" data-topic=\"Data (NumPy &amp; Pandas)\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q97<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Data (NumPy &amp; Pandas)<\/span><\/div><h3 class=\"cd-q-title\">97. Why is NumPy faster than Python lists for numerical work?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>A Python list stores pointers to separate Python objects scattered in memory, and every operation goes through the interpreter one element at a time. A NumPy array stores raw numbers of a single type in one <strong>contiguous block<\/strong>, and operations are <strong>vectorised<\/strong>: one call runs a compiled C loop over the whole array, often using CPU SIMD instructions. That makes numerical code commonly 10 to 100 times faster and far more memory-efficient. NumPy also adds broadcasting, so arrays of different shapes can be combined without writing loops.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import numpy as np, sys\n\nmarks = [56, 78, 91, 45, 88]\narr = np.array(marks)\n\nprint([m * 1.1 for m in marks])         # list: explicit loop\nprint(arr * 1.1)                        # NumPy: vectorised\nprint(arr[arr &gt; 60])                    # boolean filtering\nprint(arr.mean(), arr.std().round(2))\n\nbig_list = list(range(1_000_000))\nlist_bytes = sys.getsizeof(big_list) + sum(sys.getsizeof(x) for x in big_list)\nprint(&quot;list memory (MB):&quot;, round(list_bytes \/ 1e6, 1))\nprint(&quot;array memory (MB):&quot;, round(np.arange(1_000_000).nbytes \/ 1e6, 1))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n[61.60000000000001, 85.80000000000001, 100.10000000000001, 49.50000000000001, 96.80000000000001]\n[ 61.6  85.8 100.1  49.5  96.8]\n[78 91 88]\n71.6 18.1\nlist memory (MB): 36.0\narray memory (MB): 8.0<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-98\" data-level=\"Experienced\" data-topic=\"Data (NumPy &amp; Pandas)\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q98<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Data (NumPy &amp; Pandas)<\/span><\/div><h3 class=\"cd-q-title\">98. How do you handle missing values in a Pandas DataFrame?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>First find them with <code>df.isna().sum()<\/code>. Then choose a strategy based on the column and how much is missing:<\/p>\n<ul><li><strong>Drop<\/strong> rows or columns with <code>dropna()<\/code> when very little is missing or the column is useless.<\/li>\n<li><strong>Fill<\/strong> with <code>fillna()<\/code>: the median for skewed numbers, the mean for roughly normal ones, the mode or &#8220;Unknown&#8221; for categories.<\/li>\n<li><strong>Forward or backward fill<\/strong> (<code>ffill<\/code>, <code>bfill<\/code>) for time series.<\/li>\n<li><strong>Interpolate<\/strong> for smoothly changing numeric data.<\/li><\/ul>\n<p>For machine learning, compute fill values on the training data only, to avoid data leakage. Our <a href=\"https:\/\/codeanddebug.in\/blog\/pandas-python-roadmap\/\">Pandas roadmap<\/a> covers data cleaning in more depth.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\n    &quot;name&quot;: [&quot;Aman&quot;, &quot;Riya&quot;, &quot;Kabir&quot;, &quot;Sneha&quot;],\n    &quot;city&quot;: [&quot;Pune&quot;, None, &quot;Surat&quot;, &quot;Pune&quot;],\n    &quot;salary&quot;: [52000, 61000, np.nan, 58000],\n})\nprint(df.isna().sum().to_dict())\ndf[&quot;salary&quot;] = df[&quot;salary&quot;].fillna(df[&quot;salary&quot;].median())\ndf[&quot;city&quot;] = df[&quot;city&quot;].fillna(&quot;Unknown&quot;)\nprint(df.to_string(index=False))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n{&#x27;name&#x27;: 0, &#x27;city&#x27;: 1, &#x27;salary&#x27;: 1}\n name    city  salary\n Aman    Pune 52000.0\n Riya Unknown 61000.0\nKabir   Surat 58000.0\nSneha    Pune 58000.0<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-99\" data-level=\"Experienced\" data-topic=\"Data (NumPy &amp; Pandas)\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q99<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Data (NumPy &amp; Pandas)<\/span><\/div><h3 class=\"cd-q-title\">99. How do groupby and merge work in Pandas?<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p><code>groupby<\/code> follows <strong>split, apply, combine<\/strong>: split rows into groups by one or more columns, apply an aggregation such as <code>sum<\/code>, <code>mean<\/code> or <code>count<\/code> to each group, and combine the results into a new table. <code>agg<\/code> lets you compute several aggregations at once.<\/p>\n<p><code>merge<\/code> joins two DataFrames on common columns, like a SQL join. The <code>how<\/code> parameter selects <code>\"inner\"<\/code>, <code>\"left\"<\/code>, <code>\"right\"<\/code> or <code>\"outer\"<\/code>.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>import pandas as pd\n\norders = pd.DataFrame({&quot;customer_id&quot;: [1, 2, 1, 3, 2],\n                       &quot;amount&quot;: [500, 1200, 300, 800, 400]})\ncustomers = pd.DataFrame({&quot;customer_id&quot;: [1, 2, 4],\n                          &quot;name&quot;: [&quot;Riya&quot;, &quot;Kabir&quot;, &quot;Sneha&quot;]})\n\nsummary = orders.groupby(&quot;customer_id&quot;)[&quot;amount&quot;].agg([&quot;sum&quot;, &quot;count&quot;])\nprint(summary)\n\njoined = orders.merge(customers, on=&quot;customer_id&quot;, how=&quot;left&quot;)\nprint(joined.to_string(index=False))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n              sum  count\ncustomer_id             \n1             800      2\n2            1600      2\n3             800      1\n customer_id  amount  name\n           1     500  Riya\n           2    1200 Kabir\n           1     300  Riya\n           3     800   NaN\n           2     400 Kabir<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<section class=\"cdai cd-q\" id=\"q-100\" data-level=\"Experienced\" data-topic=\"Coding\"><div class=\"cd-q-meta\"><span class=\"cd-pill\">Q100<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Coding<\/span><\/div><h3 class=\"cd-q-title\">100. Implement an LRU cache.<\/h3><button type=\"button\" class=\"cd-btn cd-show\">Show answer<\/button><div class=\"cd-q-body\"><p>An LRU (Least Recently Used) cache has a fixed capacity. When it is full and a new key arrives, it evicts the item that was used least recently. Both <code>get<\/code> and <code>put<\/code> must run in O(1). In Python, <code>collections.OrderedDict<\/code> makes this simple: <code>move_to_end()<\/code> marks a key as recently used, and <code>popitem(last=False)<\/code> removes the oldest one. In a C++ or Java interview you would build the same thing from a hash map plus a doubly linked list, and it helps to explain that structure too.<\/p><div class=\"cdai cd-codebox\"><div class=\"cd-codehead\"><span>Python<\/span><button type=\"button\" class=\"cd-copy\">Copy<\/button><\/div><pre><code>from collections import OrderedDict\n\nclass LRUCache:\n    def __init__(self, capacity):\n        self.capacity = capacity\n        self.data = OrderedDict()\n\n    def get(self, key):\n        if key not in self.data:\n            return -1\n        self.data.move_to_end(key)          # mark as recently used\n        return self.data[key]\n\n    def put(self, key, value):\n        if key in self.data:\n            self.data.move_to_end(key)\n        self.data[key] = value\n        if len(self.data) &gt; self.capacity:\n            self.data.popitem(last=False)   # evict least recently used\n\ncache = LRUCache(2)\ncache.put(&quot;a&quot;, 1); cache.put(&quot;b&quot;, 2)\nprint(cache.get(&quot;a&quot;))\ncache.put(&quot;c&quot;, 3)          # evicts &quot;b&quot;\nprint(cache.get(&quot;b&quot;), cache.get(&quot;c&quot;), list(cache.data))<\/code><\/pre><pre class=\"cd-outp\"><code>Output:\n1\n-1 3 [&#x27;a&#x27;, &#x27;c&#x27;]<\/code><\/pre><\/div><\/div><div class=\"cd-q-foot\"><button type=\"button\" class=\"cd-btn cd-known\" aria-pressed=\"false\">Mark as known<\/button><a class=\"cd-q-top\" href=\"#cd-pyq-tool\">\u2191 Back to filters<\/a><\/div><\/section>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"predict-the-output\">Predict the output: 12 tricky Python snippets<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers love short snippets with a surprising result, because they show whether you really understand how Python works. Each one below was run on Python 3.13. Pick what you think it prints.<\/p>\n\n\n\n<div class=\"cdai cd-pyq-predict\"><span class=\"cd-tag\">Game<\/span><h4 class=\"cd-h\">What does this code print?<\/h4>\n<div class=\"cd-pp-body\"><p class=\"cd-sub\">12 snippets. Most people get 6 or 7 right on the first try.<\/p><button type=\"button\" class=\"cd-btn cd-primary cd-pp-start\">Start the challenge<\/button><\/div><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"python-interview-questions-pdf\">Download all 100 Python interview questions as a PDF<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The PDF has the same 100 questions, answers, code examples and outputs in a clean 56-page printable format, with a clickable table of contents, so you can revise offline, on your phone, or print it before your interview. It is free, with no sign-up.<\/p>\n\n\n\n<div class=\"cdai\" style=\"display:flex;flex-wrap:wrap;gap:16px;align-items:center;justify-content:space-between\">\n<div style=\"min-width:0\"><span class=\"cd-tag\">Free PDF<\/span><h4 class=\"cd-h\">100 Python Interview Questions and Answers<\/h4><p class=\"cd-sub\" style=\"margin:0\">56 pages \u00b7 Freshers, intermediate and experienced \u00b7 Tested code with outputs<\/p><\/div>\n<a class=\"cd-btn cd-dl\" href=\"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/10\/python-interview-questions-code-and-debug.pdf\" download>Download PDF<\/a><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What Python questions are asked in interviews for freshers?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Freshers are mostly asked about Python fundamentals: features of Python, data types, the difference between list and tuple, mutable and immutable objects, is vs ==, *args and **kwargs, exception handling, and simple coding problems like palindromes, prime numbers, Fibonacci and removing duplicates. Questions 1 to 40 on this page cover them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What Python topics should experienced developers prepare?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Experienced candidates should prepare the GIL and concurrency (threading, multiprocessing, asyncio), memory management and garbage collection, decorators and generators in depth, metaclasses and descriptors, performance and profiling, testing with pytest, and recent language features such as pattern matching. Data roles also need NumPy and Pandas.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How many Python interview questions should I prepare?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Quality matters more than quantity. If you can explain the 100 questions on this page in your own words and write the code examples without looking, you are well prepared for most Python interviews. Pair them with regular coding practice.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is there a PDF of these Python interview questions?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. All 100 questions with answers, code and outputs are available as a free 56-page PDF. Use the Download PDF button on this page. No sign-up is needed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Are coding questions asked in Python interviews?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, almost always. Expect at least one coding round on strings, arrays, hashing, recursion or sorting. Practise writing clean Python solutions and explaining their time complexity.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Which Python version should I prepare for?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prepare for Python 3. The examples on this page were tested on Python 3.13. Knowing a few features of recent versions, such as the walrus operator, f-string debugging and match-case, shows that you keep your skills current.<\/p>\n\n\n\n<script type=\"application\/ld+json\">{\"@context\": \"https:\/\/schema.org\", \"@type\": \"FAQPage\", \"mainEntity\": [{\"@type\": \"Question\", \"name\": \"What Python questions are asked in interviews for freshers?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Freshers are mostly asked about Python fundamentals: features of Python, data types, the difference between list and tuple, mutable and immutable objects, is vs ==, *args and **kwargs, exception handling, and simple coding problems like palindromes, prime numbers, Fibonacci and removing duplicates. Questions 1 to 40 on this page cover them.\"}}, {\"@type\": \"Question\", \"name\": \"What Python topics should experienced developers prepare?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Experienced candidates should prepare the GIL and concurrency (threading, multiprocessing, asyncio), memory management and garbage collection, decorators and generators in depth, metaclasses and descriptors, performance and profiling, testing with pytest, and recent language features such as pattern matching. Data roles also need NumPy and Pandas.\"}}, {\"@type\": \"Question\", \"name\": \"How many Python interview questions should I prepare?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Quality matters more than quantity. If you can explain the 100 questions on this page in your own words and write the code examples without looking, you are well prepared for most Python interviews. Pair them with regular coding practice.\"}}, {\"@type\": \"Question\", \"name\": \"Is there a PDF of these Python interview questions?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Yes. All 100 questions with answers, code and outputs are available as a free 56-page PDF. Use the Download PDF button on this page. No sign-up is needed.\"}}, {\"@type\": \"Question\", \"name\": \"Are coding questions asked in Python interviews?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Yes, almost always. Expect at least one coding round on strings, arrays, hashing, recursion or sorting. Practise writing clean Python solutions and explaining their time complexity.\"}}, {\"@type\": \"Question\", \"name\": \"Which Python version should I prepare for?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Prepare for Python 3. The examples on this page were tested on Python 3.13. Knowing a few features of recent versions, such as the walrus operator, f-string debugging and match-case, shows that you keep your skills current.\"}}]}<\/script>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"next-steps\">Next steps<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Turn on practice mode, go through one level at a time, and mark each question once you can answer it out loud without looking. If you are heading towards data or ML roles, continue with our <a href=\"https:\/\/codeanddebug.in\/blog\/pandas-python-roadmap\/\">Pandas roadmap<\/a> and the <a href=\"https:\/\/codeanddebug.in\/blog\/how-to-learn-ai-ml-from-scratch-roadmap\/\">interactive AI and ML roadmap<\/a>. All the best for your interview.<\/p>\n\n\n\n<script src=\"data:text\/javascript;charset=utf-8;base64,d2luZG93LkNEX1BSRUQ9W3siY29kZSI6ICJncmlkID0gW1swXSAqIDNdICogM1xuZ3JpZFswXVswXSA9IDFcbnByaW50KGdyaWQpIiwgImFuc3dlciI6ICJbWzEsIDAsIDBdLCBbMSwgMCwgMF0sIFsxLCAwLCAwXV0iLCAid2h5IjogIlRoZSBvdXRlciAqIDMgY29waWVzIHRoZSByZWZlcmVuY2UgdG8gdGhlIHNhbWUgaW5uZXIgbGlzdCB0aHJlZSB0aW1lcywgc28gY2hhbmdpbmcgb25lIHJvdyBjaGFuZ2VzIGFsbCBvZiB0aGVtLiBVc2UgW1swXSAqIDMgZm9yIF8gaW4gcmFuZ2UoMyldIGluc3RlYWQuIiwgIndyb25nIjogWyJbWzEsIDAsIDBdLCBbMCwgMCwgMF0sIFswLCAwLCAwXV0iLCAiW1sxLCAxLCAxXSwgWzAsIDAsIDBdLCBbMCwgMCwgMF1dIiwgIkVycm9yIl19LCB7ImNvZGUiOiAicHJpbnQ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3VtZW50LmNyZWF0ZVJhbmdlKCk7ci5zZWxlY3ROb2RlQ29udGVudHMoY29kZSk7dmFyIHM9d2luZG93LmdldFNlbGVjdGlvbigpO3MucmVtb3ZlQWxsUmFuZ2VzKCk7cy5hZGRSYW5nZShyKTtidC50ZXh0Q29udGVudD0iUHJlc3MgQ3RybCtDIn0KIGlmKG5hdmlnYXRvci5jbGlwYm9hcmQmJm5hdmlnYXRvci5jbGlwYm9hcmQud3JpdGVUZXh0KXtuYXZpZ2F0b3IuY2xpcGJvYXJkLndyaXRlVGV4dChjb2RlLnRleHRDb250ZW50KS50aGVuKG9rLHNlbCl9ZWxzZSBzZWwoKX0pfSk7Cn0pKCk7Cg==\"><\/script>\n","protected":false},"excerpt":{"rendered":"<p>The 100 most asked Python interview questions with clear answers and tested code, from freshers to experienced. Practice with flashcards and download the free PDF.<\/p>\n","protected":false},"author":1,"featured_media":1168,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[49],"tags":[],"class_list":["post-1169","post","type-post","status-publish","format-standard","has-post-thumbnail","category-python"],"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/10\/python-interview-questions.jpg","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1169","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=1169"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1169\/revisions"}],"predecessor-version":[{"id":1173,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1169\/revisions\/1173"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/1168"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=1169"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=1169"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=1169"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}