Python Flashcards
What is Python?
- Python is a high-level, interpreted, interactive, and object-oriented scripting language.
- Python is designed to be highly readable and compatible with different platforms such as Mac, Windows, Linux
Python is an interpreted language. Explain.
An interpreted language is any programming language where the source code is run through an interpreter which then reads statements line by line, “interpreting” the code into something the machine can understand on the fly.
This is opposed to compiled languages which must have their code parsed through a compiler that converts the source code into machine code before it can actually be run on a machine.
Programs written in Python run directly from the source code, with no intermediary compilation step.
What is the difference between lists and tuples?
Lists
Lists are mutable, i.e., they can be edited
Lists are usually slower than tuples
Lists consume a lot of memory
Lists are less reliable in terms of errors as unexpected changes are more likely to occur
Lists consist of many built-in functions.
Syntax:
list_1 = [10, ‘Intellipaat’, 20]
Tuples
Tuples are immutable (they are lists that cannot be edited)
Tuples are faster than lists
Tuples consume less memory when compared to lists
Tuples are more reliable as it is hard for any unexpected change to occur
Tuples do not consist of any built-in functions.
Syntax:
tup_1 = (10, ‘Intellipaat’ , 20)
What are the Key features of Python?
- Python is an interpreted language, so it doesn’t need to be compiled before execution
- Python is dynamically typed, so there is no need to declare a variable with the data type. Python Interpreter will identify the data type on the basis of the value of the variable.
- Python follows an object-oriented programming paradigm.
Python has classes, inheritance, and all other usual OOPs concepts.
Except Python does not have access specifiers (public and private keywords). - Python is a cross-platform language and general purpose
Explain the difference between list, tuple, and set.
List: Ordered, mutable, allows duplicates. Example: [1, 2, 3]
Tuple: Ordered, immutable, allows duplicates. Example: (1, 2, 3)
Set: Unordered, mutable, does not allow duplicates. Example: {1, 2, 3}
How do you reverse a string in Python?
Using slicing: reversed_string = string[::-1].
What are f-strings and how do you use them?
F-strings (formatted string literals) are a way to embed expressions inside string literals using curly braces {}. Example: name = “Alice”; greeting = f”Hello, {name}!”.
How do you generate random numbers in Python?
Using the random module. Example: import random; random_number = random.randint(1, 10).
What is the difference between == and is?
== checks for value equality, while is checks for identity (whether two references point to the same object).
What are *args and **kwargs?
*args allows a function to accept any number of positional arguments, while **kwargs allows a function to accept any number of keyword arguments.
What is a lambda function and where would you use it?
A lambda function is an anonymous, inline function defined using the lambda keyword. It is used for short, throwaway functions. Example: lambda x: x + 1.
List functions and time complexities?
my_list.append(item)
Adds item x to the end of the list.
O(1) (amortized)
my_list.extend(iterable)
Extends the list by appending elements from the iterable.
O(k), where k is the length of the iterable
insert(index, x)
Description: Inserts item x at a given position index.
Time Complexity: O(n), where n is the number of elements in the list after index
remove(x
Description: Removes the first occurrence of item x. Raises ValueError if not found.
Time Complexity: O(n), where n is the number of elements in the list
pop([index])
Description: Removes and returns the item at the given position index. If no index is specified, it removes and returns the last item.
Time Complexity: O(n) if index is provided (O(1) if no index is provided)
index(x[, start[, end]])
Description: Returns the index of the first occurrence of item x in the list. Raises ValueError if not found.
Time Complexity: O(n), where n is the number of elements in the list
count(x)
Description: Returns the number of occurrences of item x in the list.
Time Complexity: O(n), where n is the number of elements in the list
sort(key=None, reverse=False)
Description: Sorts the items of the list in place (i.e., the list itself is changed).
Time Complexity: O(n log n), where n is the number of elements in the list
reverse()
Description: Reverses the elements of the list in place.
Time Complexity: O(n), where n is the number of elements in the list
copy()
Description: Returns a shallow copy of the list.
Time Complexity: O(n), where n is the number of elements in the list
What are list comprehensions and give an example?
List comprehensions provide a concise way to create lists.
Example: [x for x in range(10) if x % 2 == 0] creates a list of even numbers from 0 to 9.
How do you iterate over keys and values in a dictionary?
Using the items() method.
for key, value in my_dict.items():
# code
How do you merge two dictionaries?
Using the update method or {**dict1, dict2} in Python 3.5+.
Example: dict1.update(dict2) or merged_dict = {dict1, **dict2}.
How do you add and remove items from a set?
Using add and remove methods. Example: my_set.add(item); my_set.remove(item).
What are some common use cases for sets?
Removing duplicates from a list, membership testing, and mathematical operations like union and intersection.
What is the difference between a module and a package?
A module is a single Python file, while a package is a collection of modules in directories that include a special __init__.py file.
How do you handle dependencies in a Python project?
Using a requirements file (requirements.txt) and a package manager like pip.
Example: pip install -r requirements.txt.
What is a class in Python and how do you define it?
A class is a blueprint for creating objects. It is defined using the class keyword.
Example:
class MyClass:
def __init__(self, value):
self.value = value
Explain inheritance and how it works in Python.
Inheritance allows a class to inherit attributes and methods from another class.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self): raise NotImplementedError("Subclass must implement abstract method") def info(self): return f"I am an animal named {self.name}"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call the constructor of the base class
self.breed = breed
def speak(self): return "Woof!" def info(self): return f"I am a {self.breed} named {self.name}"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name) # Call the constructor of the base class
self.color = color
def speak(self): return "Meow!" def info(self): return f"I am a {self.color} cat named {self.name}"
Create instances of the derived classes
dog = Dog(“Buddy”, “Golden Retriever”)
cat = Cat(“Whiskers”, “black”)
Call methods on the instances
print(dog.info()) # Output: I am a Golden Retriever named Buddy
print(dog.speak()) # Output: Woof!
print(cat.info()) # Output: I am a black cat named Whiskers
print(cat.speak()) # Output: Meow!
What are __init__ and __str__ methods?
__init__ is the initializer method (similar to a constructor).
__str__ returns a string representation of an object.
What are class methods, static methods, and instance methods?
Key Points:
Instance Method:
Takes self as the first parameter.
Can modify object instance state.
Can access class variables using self.__class__.
Class Method:
Takes cls as the first parameter.
Can modify class state that applies across all instances.
Accessed using cls parameter.
Defined with @classmethod decorator.
@classmethod
def class_method(cls, increment):
cls.class_variable += increment
print(f”Class method called. Class variable: {cls.class_variable}”)
Static Method:
Does not take self or cls as the first parameter.
Cannot modify object instance state or class state.
Used for utility functions related to the class.
Defined with @staticmethod decorator.
@staticmethod
def static_method(x, y):
print(f”Static method called. Sum: {x + y}”)
When to Use Each:
Instance Methods: Use when you need to access or modify the instance’s attributes or call other instance methods.
Class Methods: Use when you need to access or modify the class state or when a method logically pertains to the class itself rather than any specific instance.
Static Methods: Use when the method does not need access to the instance or class; it just logically belongs to the class’s namespace.
How do you handle exceptions in Python?
Using try, except, else, and finally blocks.
Example:
try:
# code
#Code that might raise an exception.
except Exception as e:
# handle exception: Code that runs if an exception occurs.
else:
# code if no exception: Code that runs if no exception occurs.
finally:
# cleanup code: Code that runs no matter what (used for cleanup).