Python Flashcards

Memorize unique tools for python coding language

1
Q

How to Import a Double Ended Queue

A

from collections import deqeue

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

.isalnum()

A

A method to check if the char is alphanumeric

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you manage virtual environments in Python, and why are they important?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain the difference between deepcopy() and copy() in Python. When should each be used?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the Global Interpreter Lock (GIL) in Python, and how does it affect multi-threading?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do generators work in Python, and what are the advantages of using them over regular functions?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can you describe how you would implement a decorator in Python and what use cases it addresses?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the four pillars of Object-Oriented Programming?

A

Encapsulation, Abstraction, Inheritance, Polymorphism.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is Encapsulation?

A

Bundling data and methods that operate on the data within one unit (e.g., a class). Access control is provided through private/protected members.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is Abstraction?

A

Hiding internal details and showing only essential features. Example: using a car’s interface (start, stop) without knowing the engine workings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is inheritance?

A

Creating a new class from an existing one, inheriting its properties and behaviors. Example: class Dog(Animal): pass.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is Polymorphism?

A

Methods or functions that can operate on objects of different types. Example: a run() method can be overridden in different subclasses but called uniformly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between __init__() and __new__()?

A

__new__() is responsible for creating a new instance, whereas __init__() initializes the instance’s attributes. __new__() is called before __init__().

17
Q

Method Resolution Order (MRO)?

A

When you call a method on an object, Python follows a specific order to search for that method:

Look in the class of the object first.
Then look in the classes listed in the class’s parent class (the base classes). The order in which these classes are checked is determined by the MRO.

18
Q

You need to implement a function that should use a static variable (for example, a call counter). You cannot write any code outside the function and you do not have information about external variables (outside your function). How to do it?

A

def call_counter():
# Initialize the counter if it doesn’t exist yet
if not hasattr(call_counter, ‘count’):
call_counter.count = 0 # Static variable (counter)

call_counter.count += 1  # Increment the counter
return call_counter.count  # Return the current count

Example usage
print(call_counter()) # Output: 1
print(call_counter()) # Output: 2
print(call_counter()) # Output: 3

19
Q
A