Python Flashcards
Memorize unique tools for python coding language
How to Import a Double Ended Queue
from collections import deqeue
.isalnum()
A method to check if the char is alphanumeric
How do you manage virtual environments in Python, and why are they important?
Virtual environments isolate dependencies for different projects, preventing package conflicts.
Tools like venv, virtualenv, or pyenv help manage virtual environments.
bash
Copy code
python -m venv myenv
source myenv/bin/activate
Importance: They ensure that project-specific dependencies don’t interfere with global packages or other projects, providing reproducibility and better dependency management.
Explain the difference between deepcopy() and copy() in Python. When should each be used?
copy(): Creates a shallow copy, meaning only the top-level object is copied, but nested objects are referenced.
deepcopy(): Recursively copies all objects, including nested structures.
Use case: Use copy() for lightweight structures where references are acceptable, and use deepcopy() when you need an entirely independent copy of an object, including all nested data.
What is the Global Interpreter Lock (GIL) in Python, and how does it affect multi-threading?
The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecode simultaneously in a single process.
Effect: It limits the efficiency of CPU-bound multi-threading in Python because only one thread can execute at a time. However, I/O-bound operations (e.g., network requests, file I/O) are not affected.
Solution: Use multi-processing or Python implementations like Jython or PyPy for CPU-bound tasks.
How do generators work in Python, and what are the advantages of using them over regular functions?
Generators: Functions that return an iterator and use yield instead of return. They produce values lazily, generating one value at a time.
python
Copy code
def my_generator():
yield 1
yield 2
Advantages: Generators are memory-efficient because they don’t store the entire result in memory. They are useful for handling large datasets or streams of data.
Can you describe how you would implement a decorator in Python and what use cases it addresses?
A decorator is a higher-order function that takes another function as input and extends its behavior without modifying it.
python
Copy code
def my_decorator(func):
def wrapper():
print(“Before function call”)
func()
print(“After function call”)
return wrapper
@my_decorator
def say_hello():
print(“Hello!”)
say_hello()
Use case: Decorators are used for logging, authentication, enforcing access control, performance timing, etc.
Explain how memory management works in Python. How does Python handle memory allocation and deallocation? What are some techniques you can use to optimize memory usage in your applications?
Python uses a private heap to store objects and data structures, and memory management is handled by Python’s built-in garbage collector, which uses reference counting and a cyclic garbage collector to clean up circular references. To optimize memory usage, you can use tools like memory_profiler to detect memory leaks or optimize data structures by choosing more efficient alternatives, such as using numpy arrays instead of Python lists or using slots to reduce memory overhead in classes
Can you explain the difference between concurrency and parallelism? How does Python handle both, given the limitations of the Global Interpreter Lock (GIL)? When would you use asyncio vs. threading vs. multiprocessing?
Concurrency involves multiple tasks making progress over time (but not necessarily at the same time), while parallelism involves tasks running simultaneously across multiple CPU cores. Python’s Global Interpreter Lock (GIL) limits parallelism in threads but doesn’t affect concurrency (e.g., with asyncio). For I/O-bound tasks, asyncio is suitable because it allows the program to handle many tasks asynchronously. For CPU-bound tasks, multiprocessing is better because it bypasses the GIL by creating separate processes.
How do Python decorators work? Can you give examples of common use cases for function and class decorators? What is a metaclass in Python, and how would you use one in designing a framework or library?
A decorator is a function that takes another function or class and extends or alters its behavior. For instance, @staticmethod is a class decorator in Python. You can create custom decorators like:
Metaclasses, on the other hand, are classes of classes that allow control over class creation. For example, you might use a metaclass to enforce singleton behavior by overriding the __new__ method.
What are the four pillars of Object-Oriented Programming?
Encapsulation, Abstraction, Inheritance, Polymorphism.
What is Encapsulation?
Bundling data and methods that operate on the data within one unit (e.g., a class). Access control is provided through private/protected members.
What is Abstraction?
Hiding internal details and showing only essential features. Example: using a car’s interface (start, stop) without knowing the engine workings.
What is inheritance?
Creating a new class from an existing one, inheriting its properties and behaviors. Example: class Dog(Animal): pass.
What is Polymorphism?
Methods or functions that can operate on objects of different types. Example: a run() method can be overridden in different subclasses but called uniformly.