Python Basic
Python Basic
Q: What are the fundamental built-in data types in Python? Give an example of each.
A:
Trick Q: What's the difference between list and tuple ? When would you use one over the other?
A:
Mutability: list is mutable (can be changed after creation), tuple is immutable (cannot be changed).
List: When you need a collection where elements might be added, removed, or modified (e.g., a shopping cart, a
dynamically growing list of data).
Tuple: When you need an immutable sequence, such as representing coordinates (x, y), returning multiple fixed values
from a function, or using it as a dictionary key (since dict keys must be hashable, and mutable types like lists are not).
# List example
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
# Tuple example
my_tuple = (1, 2, 3)
# my_tuple.append(4) # This would raise an AttributeError
print(my_tuple) # Output: (1, 2, 3)
A:
A:
A:
break : Terminates the loop entirely and execution continues at the statement immediately following the loop.
continue : Skips the rest of the current iteration and proceeds to the next iteration of the loop.
# break example
for i in range(10):
if i == 5:
break
print(i) # Prints 0, 1, 2, 3, 4
print("---")
# continue example
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(i) # Prints 1, 3, 5, 7, 9
Q: Define a simple function that takes two arguments and returns their sum.
A:
*args (arbitrary arguments): Allows a function to accept a variable number of non-keyword (positional) arguments. These
arguments are packed into a tuple .
**kwargs (arbitrary keyword arguments): Allows a function to accept a variable number of keyword arguments. These
A:
Class: A blueprint or a template for creating objects. It defines the structure (attributes/data) and behavior
(methods/functions) that objects of that class will have.
Object: An instance of a class. It's a concrete entity created from the class blueprint, possessing the attributes and methods
defined by the class.
A:
__init__ : This is a special method (constructor) that is automatically called when a new object of the class is created.
It's used to initialize the object's attributes.
self : Represents the instance of the class itself. It's the first parameter in any instance method (including __init__ )
and refers to the object on which the method is called. It allows you to access and modify the object's attributes and call
other methods within the same object.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
A: Inheritance is a mechanism where a new class (subclass/derived class) derives properties (attributes and methods) from an
existing class (superclass/base class). It promotes code reusability and establishes an "is-a" relationship (e.g., a "Car is a
Vehicle").
class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
buddy = Dog()
whiskers = Cat()
print(buddy.speak()) # Output: Woof!
print(whiskers.speak()) # Output: Meow!
A: Polymorphism means "many forms." In Python, it allows objects of different classes to be treated as objects of a common
superclass. It enables a single interface to be used for different data types. This is often achieved through method overriding
(where a subclass provides its own implementation of a method already defined in its superclass) or method overloading (though
Python doesn't support traditional method overloading, it achieves similar behavior through default arguments or
*args/**kwargs ). The example with Animal , Dog , and Cat 's speak() method demonstrates polymorphism. Each
animal "speaks" in its own way, but you can call animal.speak() without knowing its specific type.
A:
try : Code inside this block is executed. If an error occurs, it's caught by an except block.
except : Catches specific exceptions that occur in the try block. You can have multiple except blocks for different
error types.
else : (Optional) Code inside this block is executed only if the try block completes without raising any exceptions.
finally : (Optional) Code inside this block is always executed, regardless of whether an exception occurred or not. It's
often used for cleanup operations (e.g., closing files).
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Division successful, result:", result)
finally:
print("Execution complete.")
# List
my_list = [i * i for i in range(1000000)] # All 1M values in memory
# Generator
my_generator = (i * i for i in range(1000000)) # Values generated on demand
print(next(my_generator)) # Output: 0
print(next(my_generator)) # Output: 1
# print(my_generator[0]) # This would raise a TypeError (generators are not subscriptable)
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
fib_gen = fibonacci_generator(5)
print(list(fib_gen)) # Output: [0, 1, 1, 2, 3]
A: A decorator is a design pattern that allows you to modify or enhance the behavior of a function or class without permanently
altering its source code. It's essentially a function that takes another function as an argument, adds some functionality, and
returns a new function. Decorators are typically used with the @ syntax.
Common Use Cases: Logging, timing execution, authentication, caching, validation.
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")
# Output:
# Something is happening before the function is called.
# Hello, Alice!
# Something is happening after the function is called.
2.1. Strings
my_string = "hello"
reversed_string = my_string[::-1]
print(reversed_string) # Output: olleh
A: Strings in Python are immutable, meaning once a string is created, its content cannot be changed. Any operation that appears
to modify a string (like concatenation or slicing) actually creates a new string. This is why my_string[0] = 'H' would raise a
TypeError .
Q: Explain string immutability.
A: Strings in Python are immutable, meaning once a string is created, its content cannot be changed. Any operation that appears to modify a
string (like concatenation or slicing) actually creates a new string. This is why my_string[0] = 'H' would raise a TypeError. Core Concept:
Slicing ([start:end:step])
Slicing is a powerful way to extract portions (subsequences) from sequences like strings, lists, and tuples. Syntax : sequence[start:end:step]
end: The ending index (exclusive). If omitted, defaults to the end of the sequence.
step: The increment between elements. If omitted, defaults to 1. A negative step value reverses the sequence.
A: The most common way is to convert to a set and then back to a list (loses order). If order is important, iterate and append.
A: List comprehension provides a concise way to create lists. It's a compact and efficient way to transform or filter a sequence
(like a list or tuple) and create a new list.
# Traditional loop
squares = []
for i in range(5):
squares.append(i * i)
print(squares) # Output: [0, 1, 4, 9, 16]
# List comprehension
squares_comp = [i * i for i in range(5)]
print(squares_comp) # Output: [0, 1, 4, 9, 16]
# With condition
even_squares = [i * i for i in range(10) if i % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]
A:
Trick Q: What happens if you try to access a non-existent key in a dictionary? How can you handle it safely?
A: If you try to access a non-existent key directly ( my_dict['non_existent_key'] ), it will raise a KeyError .
Safe Handling:
Using the get() method: Returns None (or a specified default value) if the key is not found.
my_dict = {"a": 1}
def modify_list(lst):
lst.append(4)
return lst
my_list = [1, 2, 3]
new_list = modify_list(my_list)
print(my_list)
print(new_list)
A:
```
[1, 2, 3, 4]
[1, 2, 3, 4]
```
Explanation: Lists are mutable. When my_list is passed to modify_list , it's passed by object reference. Both my_list
and lst refer to the same list object in memory. Therefore, lst.append(4) modifies the original my_list object directly.
def modify_string(s):
s = s + " world"
return s
my_string = "hello"
new_string = modify_string(my_string)
print(my_string)
print(new_string)
A:
```
hello
hello world
```
Explanation: Strings are immutable. When s = s + " world" is executed inside the function, a new string object "hello
world" is created and s is made to refer to this new object. The original my_string in the global scope remains unchanged
because it still refers to the original "hello" object.
Trick Q: What's the output of this code and why? How would you fix it?
print(add_item(1))
print(add_item(2))
print(add_item(3, ['a']))
print(add_item(4))
A:
```
[1]
[1, 2]
['a', 3]
[1, 2, 4]
```
Explanation: This is a classic "trick" question. Default arguments are evaluated once when the function is defined, not every time
the function is called. So, the [] list object is created only once. Subsequent calls to add_item() without providing my_list
will reuse the same list object, leading to unexpected accumulation.
Fix: The standard way to fix this is to use None as a default value and initialize the list inside the function if None is passed.
x = 10
def outer_func():
x = 20
def inner_func():
print(x)
return inner_func
my_inner_func = outer_func()
my_inner_func()
A:
```
20
```
Explanation: This demonstrates closures and the LEGB rule (Local, Enclosing function locals, Global, Built-in). When
inner_func is defined, it "remembers" the x from its enclosing scope ( outer_func ), even after outer_func has finished
executing. So, x here refers to the x = 20 defined within outer_func , not the global x = 10 .
Trick Q: What's the output and why?
x = 10
def func():
print(x)
x = 20 # This line creates a new local x
func()
A:
```
UnboundLocalError: local variable 'x' referenced before assignment
```
Explanation: When Python encounters x = 20 inside func , it determines that x is a local variable within func . Because x is
assigned to within the function, Python expects it to be initialized before it's used. The print(x) statement tries to use x
before it's locally assigned, leading to UnboundLocalError . If x = 20 were removed, print(x) would correctly print the
global x = 10 . To modify the global x inside func , you'd need to use the global keyword.
x = 10
def func_global():
global x # Declare intent to modify global x
print(x) # Accesses global x
x = 20 # Modifies global x
func_global() # Output: 10
print(x) # Output: 20
keyboard_arrow_down 3.4. is vs ==
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2)
print(list1 is list2)
print(list1 == list3)
print(list1 is list3)
a = 5
b = 5
c = 257
d = 257
print(a == b)
print(a is b)
print(c == d)
print(c is d)
A:
* `==` (Equality operator): Compares the *values* of two objects. It checks if the objects have
* `is` (Identity operator): Compares the *identities* of two objects. It checks if two variable
* **Output:**
```
True
False
True
True
True
True
True
False
```
* **Explanation:**
* `list1 == list2`: `True` because their contents are the same.
* `list1 is list2`: `False` because `list1` and `list2` are two separate list objects in me
* `list1 == list3`: `True` (same content).
* `list1 is list3`: `True` because `list3 = list1` makes `list3` reference the *exact same
* **Integer Caching (for `a` and `b`, `c` and `d`):** Python often caches small integers (t
File I/O: Reading from and writing to files ( open() , with open() , read() , write() , readline() , readlines() ).
Modules and Packages: How to import ( import , from ... import ), purpose of __init__.py .
Virtual Environments: Why use them ( venv , conda )?
Pip: Package installer for Python.
Lambda Functions: Anonymous, small functions ( lambda x: x * 2 ).
Map, Filter, Reduce: Functional programming tools.
Error Types: Common exceptions (e.g., ValueError , TypeError , IndexError , FileNotFoundError ).
Docstrings: How to write good documentation for functions/classes.
This comprehensive overview should give you a strong foundation for your Python interview! Practice coding these snippets and explaining
the concepts in your own words. Good luck!
Sources
1. https://github.com/cyborg1432/hpkvn
2. https://cdnwebdev.com/the-ultimate-python-cheat-sheet-a-quick-reference-guide/
3. https://github.com/sakthivel-dev/python100Days
4. https://github.com/iqbalal13/PYTHON-BASIC
5. https://www.wanghao.me/pythonjijianmeixueyixingdaimawanchengde26gerichangrenwu.html
6. https://github.com/dearnidhi/Data-science-material
7. https://github.com/zerosum99/js_fluentpython_study
8. https://www.bestdivision.com/questions/is-string-a-primitive-type
9. https://github.com/shkim960520/data_structure