fresher

Fresher interview questions

Lists are mutable, meaning items can be added, removed or changed after creation, while tuples are immutable once built. Because tuples cannot change, Python can store and access them slightly more efficiently, and they are often used for fixed collections of values, such as coordinates, where changing the contents would not make sense. Lists use square brackets and tuples use parentheses, though the parentheses are optional in many contexts.

Python

A mutable object can have its internal state changed after it is created, while an immutable one cannot. Lists, dictionaries and sets are mutable, so their contents can be updated in place. Numbers, strings, tuples and frozensets are immutable, meaning any "change" actually produces a brand new object rather than modifying the original. This distinction matters most when passing objects into functions or using them as default argument values.

Python

The equality operator checks whether two objects hold the same value, while is checks whether two variables point to the exact same object in memory. Two separate list objects containing identical items will compare equal but will not be the same object, so is between them returns false. is is normally reserved for comparing against singletons such as None, since value comparisons should almost always use equality instead.

Python

A dictionary is the right choice when values need to be looked up by a meaningful key rather than by position, such as looking up a user's details by their username. A list is better when order matters and items are naturally accessed by their position or iterated in sequence. Dictionaries also offer near constant time lookups regardless of size, which a list cannot match once it grows large and needs a linear search.

Python

A set is an unordered collection that automatically enforces uniqueness, so adding the same value twice has no visible effect since only one copy is ever kept. Internally it works like a dictionary with only keys and no values, using hashing to check membership quickly. Sets are commonly used to remove duplicates from a list or to test whether an item exists in a collection very fast.

Python

The three common approaches are f-strings, the format method and the older percent-style formatting. F-strings, written with an f before the opening quote, let you embed expressions directly inside curly braces and are now the preferred style for their readability and speed. The format method achieves the same result with placeholders filled in afterward, while percent formatting is an older, C-style approach still seen in legacy code.

Python

*args collects any extra positional arguments passed to a function into a tuple, letting the function accept a variable number of inputs without naming each one. **kwargs does the same for keyword arguments, collecting them into a dictionary of name and value pairs. Both are commonly used when writing a function that needs to pass extra arguments through to another function without knowing in advance what they will be.

Python

self refers to the specific object the method is being called on, letting the method read and update that object's own attributes rather than some other instance of the same class. It is passed automatically by Python whenever a method is called on an object, which is why it must be listed as the first parameter in the method definition even though it is never supplied explicitly by the caller.

Python

__init__ is the constructor that runs automatically the moment a new object is created from a class, and its usual job is to set up the object's starting attributes based on whatever arguments were passed in. Without it, a newly created object would have no attributes assigned at all, requiring them to be set individually after creation instead of arriving ready to use.

Python

A class variable is defined directly inside the class body and is shared by every instance of that class, so changing it through the class itself affects all objects at once. An instance variable is usually set inside __init__ using self, and each object gets its own independent copy. Confusing the two is a common source of bugs, especially with mutable class variables that unexpectedly end up shared across every instance.

Python

A class can be defined to inherit from another by listing the parent class in parentheses after the class name, which automatically gives the child class every attribute and method the parent defines. The child can then add new behaviour of its own or override an inherited method by redefining it with the same name, letting related classes share common logic while still customising the parts that differ.

Python

super() gives access to methods defined on a parent class from within a child class, most commonly used inside an overridden __init__ to run the parent's setup logic before adding anything specific to the child. This avoids repeating the parent's initialization code and keeps the relationship between the two classes explicit, rather than hardcoding the parent class name directly.

Python

A list comprehension builds a new list in a single, compact expression by looping over an existing iterable and optionally filtering it, instead of writing a separate for loop that appends to an empty list step by step. Beyond being shorter, comprehensions are usually a little faster too, since the looping happens internally rather than through repeated method calls, though very complex logic is often clearer written as a normal loop instead.

Python

A dictionary comprehension is the same idea as a list comprehension applied to building a dictionary, producing key and value pairs from an iterable in one expression rather than looping and assigning entries one at a time. It is especially handy for transforming an existing dictionary or building a lookup table from two related sequences without several lines of manual looping code.

Python

Slicing extracts a portion of a sequence using a start position, a stop position and an optional step, separated by colons inside square brackets. Leaving the start or stop empty defaults to the beginning or end of the sequence, and a negative step reverses the direction, which is the common trick behind reversing a string or list in one line. The stop position is never included in the result, only values up to but excluding it.

Python

append adds a single item to the end of a list exactly as given, so appending another list adds that whole list as one nested element. extend instead adds each item from the given iterable individually, flattening it into the original list one element at a time. Mixing the two up is a common beginner mistake that results in an unexpectedly nested list.

Python

remove searches for the first matching value and deletes it, raising an error if the value is not present. pop removes and returns the item at a given position, defaulting to the last item if no index is given, which makes it useful when the removed value is still needed. del is a general statement that can remove an item by position, delete a slice, or remove a variable entirely, and it does not return anything.

Python

Code that might raise an error is placed inside a try block, and if an exception occurs, control jumps immediately to a matching except block instead of crashing the program. A finally block, if present, always runs afterward regardless of whether an exception was raised or caught, making it the natural place for cleanup work such as closing a file or a network connection.

Python

A custom exception is usually created by defining a new class that inherits from Exception, or from a more specific built-in exception if one fits, and then raising an instance of it with the raise keyword wherever the error condition is detected. This lets calling code catch that specific exception type by name, which communicates the problem far more clearly than raising a generic exception with only a text message.

Python

None represents the absence of a value and is Python's equivalent of null in other languages, often returned by a function that has nothing meaningful to give back. The correct way to check for it is with is None or is not None rather than an equality comparison, since None is a single unique object and identity comparison is both clearer in intent and marginally faster.

Python

A local variable is created inside a function and only exists while that function is running, disappearing once it returns. A global variable is defined at the top level of a module and can be read from inside any function without special treatment. To actually assign to a global variable from inside a function, rather than just read it, the function must declare it with the global keyword first, otherwise Python creates a new local variable instead.

Python

pass is a statement that does nothing at all, used purely as a placeholder wherever Python's syntax requires a block of code but nothing needs to happen yet, such as an empty function body or an unfinished branch of an if statement. Without something in that spot, the code would fail to parse at all, since an empty indented block is not valid on its own.

Python

break stops the loop entirely and jumps to the first line after it, useful once whatever the loop was searching for has already been found. continue skips only the rest of the current pass through the loop body and moves straight on to the next iteration, without ending the loop as a whole. Mixing the two up is an easy mistake when a loop needs to skip certain items rather than stop altogether.

Python

A lambda is a small, unnamed function defined in a single line using the lambda keyword, typically used for a short piece of logic needed only once, such as a custom sort key or a quick condition passed into another function. Unlike a regular function defined with def, a lambda can only contain a single expression and cannot include statements like loops or multiple lines of logic.

Python

map applies a given function to every item in an iterable and produces a new sequence of the results, while filter keeps only the items for which a given function returns true, discarding the rest. Both achieve what could also be written as a for loop with an if statement or an append call, but they express the intent more compactly, and are often paired with a lambda for the function argument.

Python

PEP 8 is Python's official style guide, describing conventions such as indentation width, naming styles for variables and functions, and how to space out operators and imports. Following it is not enforced by the language itself, but consistent style makes code far easier for other developers, and your future self, to read, and most teams and open-source projects expect contributions to follow it closely.

Python

Python uses indentation itself as the way to mark where a block of code, such as the body of a function or an if statement, begins and ends, rather than relying on symbols like curly braces. This was a deliberate design choice to force consistently readable code, since the visual structure of the code always matches its actual logical structure, but it also means inconsistent indentation is a syntax error rather than just a style complaint.

Python

A shallow copy creates a new outer object but still shares references to the same nested objects inside it, so changing a nested list inside a shallow copy also changes it in the original. A deep copy recursively copies every nested object as well, producing a completely independent structure with no shared references at all. The copy module provides both a shallow copy function and a deep copy function for exactly this purpose.

Python

len() returns the number of items in a collection, working on any built-in type that has a defined length, including strings, lists, tuples, dictionaries and sets. For a string it returns the number of characters, and for a dictionary it returns the number of key and value pairs rather than anything about their contents. Calling it on an object with no defined length raises a type error.

Python

range() produces a sequence of numbers lazily, generating each value only as it is needed rather than storing every number in memory at once, which makes it extremely memory efficient even for a very large range. A literal list of the same numbers stores every single value up front. In practice range() is almost always used for looping a fixed number of times, and converted to an actual list only if the full sequence is genuinely needed.

Python

An immutable string cannot be changed after it is created, so any operation that looks like it modifies a string, such as concatenation or replacing a character, actually builds and returns a brand new string object instead. This makes strings safe to share freely without worrying that one part of a program might unexpectedly change a value another part is relying on, though it also means repeatedly building up a large string in a loop can be less efficient than using a list and joining it once at the end.

Python

Python caches small integers and some short strings internally for efficiency, so two separate variables holding the same small value may happen to point to the identical cached object, making is return true by coincidence. This behaviour is an implementation detail, not a guarantee, and larger numbers or dynamically built strings will not be cached the same way, so relying on is for value comparison is fragile and should always be avoided in favour of equality.

Python

The recommended pattern is a with block using open(), which guarantees the file is closed automatically once the block finishes, even if an error occurs while reading it. Without the with block, the file would need to be closed manually, and forgetting to do so is a common source of bugs, particularly on systems where an open file can block other programs from accessing it.

Python

A module is simply a single Python file containing definitions and code that can be imported elsewhere. A package is a folder containing multiple related modules, along with a special init file that marks it as a package, letting a larger project organise many modules under one importable namespace. In short, a package is a collection of modules grouped together, while a module is the individual file itself.

Python

Importing a whole module keeps every name inside it accessible only through the module's own name, which avoids naming clashes but requires typing the module name each time something inside it is used. Importing specific names directly brings just those names into the current file, letting them be used without a prefix, which is more convenient but riskier if two different modules happen to define something with the same name.

Python

The core built-in types cover numbers such as integers and floating point values, text through strings, and several ways of grouping data: lists and tuples for ordered sequences, dictionaries for key and value pairs, and sets for unique unordered collections, alongside the boolean type for true and false values. Almost every Python program is built from some combination of these handful of fundamental types.

Python

Type casting converts a value from one type to another, such as turning the text a user typed into an actual number before doing arithmetic with it. It is done by calling the target type as a function on the value, for example wrapping a string in int() or float(), and it raises an error if the value cannot sensibly be converted, such as trying to turn the word "hello" into a number.

Python

A docstring is a string literal placed as the very first statement inside a function, class or module, describing what it does, and unlike a regular comment it is stored as part of the object itself and can be retrieved at runtime with the help function or a tool's documentation generator. Writing a clear docstring is one of the simplest habits that makes a codebase noticeably easier for other people, or a future version of yourself, to understand.

Python

A function is a standalone block of reusable code defined independently, called by its own name. A method is essentially the same idea but defined inside a class and called on an object of that class, automatically receiving that object as its first argument through self. Every method is technically a function, but not every function is a method, since plain functions are not tied to any particular class.

Python

A function with no return statement, or one that reaches the end of its body without hitting a return, automatically hands back None to whoever called it. This surprises beginners fairly often, since calling such a function and trying to use its result usually leads to confusing errors later on, when the code assumes it received a real value but actually received nothing at all.

Python

A function can return several values at once by separating them with commas after the return keyword, which Python automatically packages into a tuple behind the scenes. The caller can then either treat the result as a single tuple or immediately unpack it into separate variables in one line, which is the far more common and readable pattern seen in real code.

Python

Unpacking assigns the individual elements of a list, tuple or other iterable directly to separate variables in a single statement, instead of accessing each item by its position one at a time. An asterisk can also be used to capture any remaining items into a single list while unpacking the rest normally, which is handy when only the first item or two actually matter and the rest can be gathered together.

Python

enumerate() wraps an iterable and produces pairs of a running index alongside each item, letting a for loop access both the position and the value at the same time without manually creating and incrementing a counter variable. It reads more cleanly than tracking an index by hand, and it is the idiomatic way to write this kind of loop in Python.

Python

zip() takes two or more iterables and combines them element by element into pairs, or larger tuples for more than two iterables, stopping as soon as the shortest one runs out of items. It is commonly used to loop over two related lists at the same time, such as a list of names alongside a matching list of ages, without manually indexing into both.

Python

Python's conditional expression lets a value be chosen based on a condition in a single line, written as one value if the condition holds else another value, rather than spreading a full if and else block across several lines just to pick between two options. It is best kept for short, simple choices, since chaining several of them together quickly becomes far harder to read than an ordinary if statement.

Python