Example: Lists are mutable (my_list[0] = 'new_value'), while strings are immutable (my_str[0] = 'n' will raise an error).
Example: List: my_list[0], Dictionary: my_dict['key']
Example: Two lists with the same content (list1 == list2 is True) may still occupy different memory locations (list1 is list2 is False).
Example: Converting a float to an integer: int(4.75) results in 4. Converting a string to an integer: int('123') results in 123.
// performs floor division and returns the largest integer less than or equal to the result, while / performs regular division and returns a float.
Python evaluates operators based on their precedence, with higher precedence operators (like *, /) being evaluated before lower precedence operators (like +, -). Parentheses can be used to override the default precedence.
Python uses LEGB (Local, Enclosing, Global, Built-in) rule for variable scope. Variables declared inside a function are local to that function unless declared global.
A global variable is declared outside all functions and is accessible throughout the program, while a local variable is declared inside a function and is only accessible within that function.
Example: # Global Variable x = 10 # Global variable def my_function(): # Local Variable y = 5 # Local variable print("Inside function, local y:", y) print("Inside function, global x:", x) # Accessing the global variable inside the function my_function() # Trying to access local variable outside function print("Outside function, global x:", x) # Can access global variable # print(y) # This will raise an error because y is a local variable Output Inside function, local y: 5 Inside function, global x: 10 Outside function, global x: 10
Python is dynamically typed, so you declare a variable simply by assigning a value to it,
e.g., x = 10. The variable’s type is determined at runtime.
Variable shadowing occurs when a local variable in a function has the same name as a global variable. The local variable temporarily "shadows" the global variable within the function’s scope.
Yes, you can assign multiple variables in a single line like this:
a, b, c = 1, 2, 3.
Positive indexing starts from 0, where list[0] is the first element.
Negative indexing starts from -1, where list[-1] is the last element.
example: my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry'] #Accessing elements using positive indexing print(my_list[0]) # First element print(my_list[2]) # Third element my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry'] # Accessing elements using negative indexing print(my_list[-1]) # Last element print(my_list[-3]) # Third element from the end
Example: my_list[2] = 'new_value'
Python raises an IndexError if you attempt to access an index that is beyond the range of the list.
You can concatenate two lists using the + operator, like this: list1 + list2.
A tuple is immutable (cannot be changed after creation), <>br> while a list is mutable (can be changed).
No, tuples are immutable, so you cannot modify their elements after they are created.
Elements in a tuple are accessed via indexing, just like lists. For example, my_tuple[1] returns the second element.
Yes, tuples can store elements of different data types, similar to lists.
You can create a tuple with a single element by adding a comma after the element, like this: (5,).
A dictionary stores key-value pairs, while a list stores a sequence of values. Dictionary keys are unique, and values are accessed using keys, not indices.
You can add a key-value pair by assigning a value to a key.
Example: my_dict['new_key'] = 'new_value'
Python raises a KeyError if you try to access a key that is not present in the dictionary.
No, dictionary keys must be immutable data types like strings, numbers, or tuples. Lists cannot be used as dictionary keys.
Starting from Python 3.7, dictionaries maintain insertion order, meaning the order in which key-value pairs are added is preserved.
A set is an unordered collection of unique elements, while a list is ordered and can contain duplicate values.
No, sets automatically remove duplicates, ensuring that each element is unique.
You can add an element using the add() method, like this: my_set.add('element').
Sets are unordered collections, so the elements do not have a defined order and cannot be accessed via indexing.
Yes, sets can contain elements of different data types, as long as they are immutable (e.g., integers, strings, tuples).
A function is a block of reusable code that performs a specific task and is defined using the def keyword. It can be called from anywhere in the program.
A method is a function that is associated with an object or class. It is called on an object, and its behavior can depend on the object’s state.
Example: # Function def greet(): return "Hello, World!" # Method (associated with a string object) s = "Hello" print(s.lower()) # Calling a method on a string object
In Python, you can define default values for function parameters. If the function is called without arguments for those parameters, the default values are used.
Example: def greet(name="Guest"): return f"Hello, {name}!" print(greet()) # Output: Hello, Guest! print(greet("Alice")) # Output: Hello, Alice!
*args allows a function to accept any number of positional arguments.
**kwargs allows a function to accept any number of keyword arguments.
Example: def demo_args(*args): for arg in args: print(arg) def demo_kwargs(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") demo_args(1, 2, 3) # Output: 1, 2, 3 demo_kwargs(name="John", age=30) # Output: name: John, age: 30
A lambda function is a small, anonymous function defined using the lambda keyword. It can have any number of arguments but only one expression. Lambda functions are often used for short, throwaway functions.
Example: # Regular function def add(x, y): return x + y # Lambda function add_lambda = lambda x, y: x + y print(add(3, 4)) # Output: 7 print(add_lambda(3, 4)) # Output: 7
The return statement in a function sends the result of the function back to the caller and terminates the function execution. Yes, a function can return multiple values by separating them with commas, and these values are returned as a tuple.
Example: def get_details(): name = "John" age = 25 return name, age # Returning multiple values as a tuple result = get_details() print(result) # Output: ('John', 25) print(result[0]) # Output: John print(result[1]) # Output: 25
A module is a single Python file containing functions, classes, or variables, whereas a package is a collection of modules grouped together in a directory, often with an __init__.py file.
Third-party Python packages can be installed using pip, the package manager for Python.
Example: pip install requests
You can import a specific function using the from keyword.
Example: from my_package.my_module import my_function
To create a package, organize your code into modules (Python files), place them in a directory, and include an __init__.py file. The __init__.py file can be empty or contain initialization code.
You can use pip list to view all installed packages in your Python environment.
OOP is a programming paradigm based on the concept of "objects", which are instances of classes. It allows for encapsulation, inheritance, and polymorphism.
The __init__() method is a constructor used to initialize the object's attributes when a new instance of a class is created.
Inheritance allows a class to inherit properties and methods from another class.
Example: class Animal: def speak(self): return "Animal speaks" class Dog(Animal): def bark(self): return "Dog barks" d = Dog() print(d.speak()) # Inherits speak method
Class variables are shared among all instances of a class, while instance variables are unique to each instance.
Polymorphism allows different classes to implement the same method in different ways.
Example: A Dog and Cat class can both implement a speak() method, but the method behaves differently in each class.
Encapsulation is achieved by restricting access to certain attributes or methods using private (__) or protected (_) access modifiers.
Multiple inheritance allows a class to inherit from more than one class.
Example: class A: def method_a(self): return "Method A" class B: def method_b(self): return "Method B" class C(A, B): pass c = C() print(c.method_a(), c.method_b())
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
@staticmethod: A method that does not modify class or instance state. It doesn’t take self or cls as arguments.
@classmethod: A method that takes cls as its first argument and can modify class-level state.
Inheritance models an "is-a" relationship, where a subclass inherits properties and methods from a superclass.
Composition models a "has-a" relationship, where an object contains other objects as attributes.
Operator overloading allows you to define custom behavior for operators (e.g., +, -, *, ==) in your own classes by implementing special methods like __add__(), __eq__(), etc.
By defining the __add__() method in the class.
Example: Example: class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y)
Yes, by defining the __eq__() method in your class.
You need to handle type-checking inside the overloaded method to avoid comparison errors. Otherwise, it may result in a TypeError.
Yes, by defining the __getitem__() and __setitem__() methods, you can overload the indexing operator.
Exception handling allows you to manage runtime errors gracefully, preventing the program from crashing by using try, except, finally, and raise.
You can raise an exception using the raise keyword.
Example: raise ValueError("Invalid value")
try-except handles exceptions that occur within the try block.
try-finally guarantees that the finally block will be executed whether or not an exception occurs.
Yes, you can have multiple except blocks to handle different types of exceptions.
The else block is executed if no exceptions are raised in the try block.
A regular expression (RegEx) is a pattern used to match strings. Python’s re module provides functions for working with regular expressions.
You can use the re.search() function
Example: import re match = re.search(r'\d+', 'abc123')
You can use the re.sub() function to replace all occurrences of a pattern with a given string.
\d: Matches any digit (0-9).
\w: Matches any word character (alphanumeric and underscore).
\s: Matches any whitespace character.
You can use re.split() to split a string by a regular expression pattern..
Example: import re # String with multiple delimiters (commas, semicolons, spaces) text = "apple, banana; cherry orange" # Use regular expression to split by commas, semicolons, or spaces result = re.split(r'[,\s;]+', text) print(result) #Output ['apple', 'banana', 'cherry', 'orange']
You can use the open() function to open a file. Modes include:
'r': Read (default)
'w': Write
'a': Append
'b': Binary mode
You can use the read() method to read the entire contents of a file into memory.
Example: with open('file.txt', 'r') as f: content = f.read()
read() reads the entire file.
readline() reads one line at a time.
super() is used to call a method from the parent class. It is particularly useful in multiple inheritance scenarios to ensure that the method resolution order (MRO) is followed correctly.
Example: class A: def __init__(self): print("A's __init__") class B(A): def __init__(self): super().__init__() print("B's __init__") class C(A): def __init__(self): super().__init__() print("C's __init__") class D(B, C): def __init__(self): super().__init__() print("D's __init__") d = D() Output: A's __init__ C's __init__ B's __init__ D's __init__ In this example, super() ensures that A's __init__ is only called once, despite the multiple inheritance.
Duck typing is a concept related to dynamic typing in Python. It means that the suitability of an object is determined by the presence of certain methods and properties, rather than the actual type of the object.
Example: class Duck: def quack(self): print("Quack!") class Person: def quack(self): print("I'm quacking like a duck!") def in_the_forest(duck): duck.quack() d = Duck() p = Person() in_the_forest(d) # Quack! in_the_forest(p) # I'm quacking like a duck! In this example, both Duck and Person objects can be passed to in_the_forest() function because they both have a quack method.
The match statement is a feature introduced in Python 3.10, used for structural pattern matching. It allows for checking a value against a pattern
Example: def http_status(status): match status: case 200: return "OK" case 404: return "Not Found" case 500: return "Internal Server Error" case _: return "Unknown status" print(http_status(200)) # OK print(http_status(404)) # Not Found print(http_status(500)) # Internal Server Error print(http_status(403)) # Unknown status
There are many ways to a reverse a string in Python one way is using slicing.
Example: s = "Hello, World!" reversed_s = s[::-1] print(reversed_s) # !dlroW ,olleH
The map() function applies a given function to all items in an iterable (like a list) and returns a map object (an iterator).
Example: def square(n): return n * n numbers = [1, 2, 3, 4, 5] squared_numbers = map(square, numbers) print(list(squared_numbers)) # [1, 4, 9, 16, 25]
Instance Variables are variables that are specific to each object. They are defined in the __init__ method and are prefixed with self.
Example: class Dog: species = "Canis familiaris" # Class Variable def __init__(self, name, age): self.name = name # Instance Variable self.age = age # Instance Variable dog1 = Dog("Buddy", 5) dog2 = Dog("Molly", 7) print(dog1.species) # Canis familiaris print(dog2.species) # Canis familiaris print(dog1.name) # Buddy print(dog2.name) # Molly
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method in the subclass should have the same name and signature as the method in the superclass.
Example: class Animal: def sound(self): return "Some sound" class Dog(Animal): def sound(self): return "Bark" class Cat(Animal): def sound(self): return "Meow" dog = Dog() cat = Cat() print(dog.sound()) # Bark print(cat.sound()) # Meow In this example, the sound method is overridden in the Dog and Cat subclasses to provide specific sounds.