Python Guide for Beginners: Concepts, Code and Interview Questions
Updated 28 Oct 2026 6 min read
On this page 15 sections
- 1Why Python, and how interviews use it
- 2Variables, types and the "everything is an object" idea
- 3Mutable vs immutable
- 4Control flow and loops
- 5Core data structures and their costs
- 6Strings
- 7Comprehensions
- 8Functions, scope and arguments
- 9Decorators and generators
- 10Exceptions and files
- 11Object-oriented Python
- 12Interview concepts that trip people up
- 13Coding-round habits in Python
- 14Frequently asked Python interview questions
- 15A 4-week practice plan
Why Python, and how interviews use it
Python is readable, versatile and in demand for backend development, automation, data analysis, machine learning and testing. It is also the language many candidates choose for coding rounds because you can express an idea in few lines. Interviewers rarely ask trivia about syntax. They ask whether you understand how Python behaves: mutability, references, scope, iteration, errors and the cost of operations. This guide covers the concepts in the order they usually come up. Pair it with the roadmap for your target role, such as data analyst or backend developer, and with the DSA study plan.
Install Python from python.org and use VS Code, or use Google Colab if you cannot install anything yet. Run every example yourself; reading is not enough.
1. Variables, types and the "everything is an object" idea
name = "Asha" # str
age = 21 # int
price = 99.5 # float
is_student = True # bool
nothing = None # NoneType
print(type(age)) # <class 'int'>
print(f"{name} is {age}")
Python is dynamically typed (the type belongs to the value, not the variable) and strongly typed ("5" + 5 raises an error instead of guessing). Variables are names that refer to objects. This single idea explains many interview questions:
a = [1, 2, 3]
b = a # b points to the SAME list
b.append(4)
print(a) # [1, 2, 3, 4]
c = a.copy() # a new list (shallow copy)
c.append(5)
print(a) # [1, 2, 3, 4] unchanged
Know is (same object) vs == (equal value), id(), and that None should be compared with is None.
2. Mutable vs immutable
- Immutable:
int,float,str,tuple,frozenset,bytes - Mutable:
list,dict,set
Immutable objects can be dictionary keys and set members because they are hashable. A shallow copy copies the outer container only, while a deep copy (copy.deepcopy) also copies nested objects.
Classic trap: mutable default arguments.
def add_item(item, bucket=[]): # the list is created ONCE
bucket.append(item)
return bucket
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] surprising!
def add_item_safe(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
This appears in a huge number of interviews. Explain that default values are evaluated once, when the function is defined.
3. Control flow and loops
marks = 72
if marks >= 75:
grade = "Distinction"
elif marks >= 40:
grade = "Pass"
else:
grade = "Fail"
for i in range(1, 6):
print(i * i)
for index, value in enumerate(["a", "b", "c"], start=1):
print(index, value)
for x, y in zip([1, 2, 3], ["one", "two", "three"]):
print(x, y)
Useful: break, continue, and the lesser-known for ... else (the else runs if the loop was not broken). Indentation defines blocks, so use four spaces consistently.
4. Core data structures and their costs
nums = [4, 8, 15, 16] # list: ordered, changeable
nums.append(23)
point = (3, 4) # tuple: ordered, fixed
unique = {1, 2, 2, 3} # set -> {1, 2, 3}
student = {"name": "Ravi", "age": 20} # dict
print(student.get("city", "unknown"))
| Operation | list | dict / set |
|---|---|---|
| Access by index / key | O(1) | O(1) average |
Search (in) |
O(n) | O(1) average |
| Append | O(1) amortised | O(1) average |
| Insert or delete at the front | O(n) | n/a |
Being able to say "I used a set because membership checks are O(1)" is the kind of reasoning interviewers want. Use collections too: Counter (frequencies), defaultdict (no key errors), deque (fast pops from both ends) and heapq for priority queues.
from collections import Counter, defaultdict, deque
import heapq
print(Counter("banana")) # Counter({'a': 3, 'n': 2, 'b': 1})
groups = defaultdict(list)
for word in ["eat", "tea", "tan"]:
groups["".join(sorted(word))].append(word)
# {'aet': ['eat', 'tea'], 'ant': ['tan']}
5. Strings
Strings are immutable. Know slicing, split, join, strip, replace, startswith, find and f-strings.
s = "interview"
print(s[::-1]) # 'weivretni' reversed
print(s[2:6]) # 'terv'
print(" ".join(["a", "b"])) # 'a b'
def is_palindrome(text):
cleaned = [c.lower() for c in text if c.isalnum()]
return cleaned == cleaned[::-1]
Building a string with += in a loop is slow for large inputs. Collect parts in a list and "".join(parts).
6. Comprehensions
squares = [x * x for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]
lookup = {w: len(w) for w in ["red", "green"]} # {'red': 3, 'green': 5}
unique_lengths = {len(w) for w in ["a", "bb", "cc"]}
Use them for simple transformations; switch to a normal loop when the logic gets complicated.
7. Functions, scope and arguments
def greet(name, greeting="Hello", *args, **kwargs):
return f"{greeting}, {name}!"
print(greet("Asha"))
print(greet(name="Ravi", greeting="Hi"))
*argscollects extra positional arguments (a tuple);**kwargscollects extra keyword arguments (a dict)- Scope (LEGB): Local, Enclosing, Global, Built-in. Use
globalandnonlocalsparingly. - Functions are first-class objects: you can pass them around, return them and store them
- Lambda:
sorted(words, key=lambda w: len(w)) - Know
map,filterandsortedwithkey
Closures are functions that remember variables from the place they were defined:
def make_counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
c = make_counter()
print(c(), c()) # 1 2
8. Decorators and generators
A decorator wraps a function to add behaviour, such as logging or timing.
import functools, time
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = fn(*args, **kwargs)
print(f"{fn.__name__} took {time.perf_counter() - start:.4f}s")
return result
return wrapper
@timed
def slow_sum(n):
return sum(range(n))
A generator produces values one at a time with yield, using almost no memory, which is ideal for large files and streams.
def read_big_file(path):
with open(path) as f:
for line in f:
yield line.strip()
squares = (x * x for x in range(10**6)) # generator expression
Difference between an iterable (can be looped over), an iterator (has __next__) and a generator (an iterator made with yield) is a frequent question.
9. Exceptions and files
def read_number(text):
try:
return int(text)
except ValueError:
return None
finally:
pass # always runs
with open("data.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
Catch specific exceptions, never a bare except:. Use raise to signal problems, create custom exceptions by subclassing Exception, and use with (context managers) so files and connections close even on errors.
10. Object-oriented Python
class Account:
bank = "JobCobalt Bank" # class attribute
def __init__(self, owner, balance=0):
self.owner = owner # instance attributes
self._balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
self._balance += amount
@property
def balance(self):
return self._balance
def __repr__(self):
return f"Account({self.owner!r}, {self._balance})"
@classmethod
def from_string(cls, text):
owner, balance = text.split(",")
return cls(owner, int(balance))
@staticmethod
def is_valid_amount(x):
return x > 0
Know self, inheritance (class Savings(Account) and super()), polymorphism, dunder methods (__init__, __str__, __eq__, __len__), the difference between @classmethod and @staticmethod, and the ideas behind OOP (OOP and design principles). Python supports multiple inheritance, resolved by the MRO (method resolution order).
11. Interview concepts that trip people up
- GIL (Global Interpreter Lock): in CPython, only one thread executes Python bytecode at a time, so threads do not speed up CPU-heavy work. Use
multiprocessingfor CPU-bound tasks and threads orasynciofor I/O-bound ones. - Memory management: reference counting plus a cyclic garbage collector
listvstuple: mutability, hashability, small speed and memory advantages for tuples__name__ == "__main__": code that runs only when the file is executed directly- Shallow vs deep copy,
isvs==, and the mutable default argument - Virtual environments (
python -m venv .venv) andpip install -r requirements.txtkeep project dependencies separate - Type hints (
def area(r: float) -> float:) improve readability and tooling
12. Coding-round habits in Python
# two-sum with a dictionary: O(n)
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i
return []
Tips for coding rounds:
- Restate the problem and ask about input size, duplicates, empty input and negative numbers
- Describe a brute-force solution first, then improve it and state the time and space complexity
- Use built-ins confidently (
sorted,set,Counter,enumerate,zip), but know what they do under the hood - Avoid modifying a list while iterating over it
- Watch out for recursion limits (default around 1,000); use iteration or a stack for deep recursion
- Test with a small example and edge cases before saying you are done (online assessment tips)
13. Frequently asked Python interview questions
- What are Python's key features? (interpreted, dynamically typed, high-level, large standard library)
- Difference between list, tuple, set and dictionary
- What is mutability? Give examples
- What are
*argsand**kwargs? - What is a decorator? What is a generator?
- Explain the GIL
- How does Python manage memory?
- What is the difference between
deepcopyandcopy? - What are list comprehensions, and when would you avoid them?
- How do you handle exceptions? What is
finally? - What is
self? What are__init__and__str__? - How would you remove duplicates from a list while keeping the order? (
list(dict.fromkeys(items)))
14. A 4-week practice plan
- Week 1: syntax, strings, lists, dictionaries; solve 25 beginner problems
- Week 2: functions, comprehensions, files, exceptions; write a small command-line tool
- Week 3: OOP, decorators, generators; build a project such as an expense tracker with file storage
- Week 4: solve 20 interview-style problems (arrays, strings, hash maps) and revise the questions above
Then build something real: a web scraper, an API with Flask or FastAPI, or a data-analysis notebook, and put it on GitHub (Git guide, portfolio projects).
Found this useful? Share it with a friend.