Python Debugging and Essential Features: pdb, yield, and List-to-Tuple Conversion

This guide covers key Python features for developers: using the pdb debugger for efficient code troubleshooting, understanding the `yield` keyword for creating memory-efficient generators, and converting lists to immutable tuples using the `tuple()` function.



Python Coding Interview Questions

Debugging Python Code

Question 1: Debugging Python Programs

The Python debugger (`pdb`) is used for debugging. You can start the debugger by running your script with the command: `python -m pdb myscript.py`. This will start your script in debug mode, allowing you to step through the code line by line.

`yield` Keyword

Question 2: Python `yield` Keyword

The `yield` keyword in Python transforms a function into a generator. A generator produces a sequence of values one at a time, pausing execution between each yield. It is memory-efficient for generating large sequences.

Python Code

def creating_gen(index):
    months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
    yield months[index]
    yield months[index + 2]

next_month = creating_gen(3)
print(next(next_month), next(next_month))  # Output: apr jun

Converting Lists to Tuples

Question 3: Converting Lists to Tuples

Use the `tuple()` function to convert a list into a tuple. Tuples are immutable (their values cannot be changed after creation).

Python Code

month = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
converting_list = tuple(month)
print(converting_list)  # Output: ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
print(type(converting_list))  # Output: <class 'tuple'>

NumPy Arrays

Question 4: NumPy Arrays

NumPy arrays in Python are efficient for numerical computations. They are generally faster and consume less memory compared to standard Python lists. NumPy arrays are multidimensional arrays, making them suitable for working with matrices and other multidimensional data.

Creating Empty NumPy Arrays

Question 5: Creating Empty NumPy Arrays

Two ways to create an empty NumPy array:

Python Code

import numpy
array_1 = numpy.array([])
print(array_1)       # Output: []
array_2 = numpy.empty(shape=(3, 3))
print(array_2)       # Output: (A 3x3 array with uninitialized values; values will vary)

Negative Indexing

Question 6: Negative Indexing in Python

Negative indexing in Python allows accessing elements from the end of a sequence. my_list[-1] accesses the last element; my_list[-2] accesses the second-to-last element, and so on.

Python Code

a = [4, 6, 8, 3, 1, 7]
print(a[-3])  # Output: 3
print(a[-5])  # Output: 6
print(a[-1])  # Output: 7

Python Sets

Question 8: Python Sets

A set is an unordered collection of unique, immutable items. Sets are useful for membership testing and eliminating duplicate values.

Generating Random Numbers

Question 9: Generating Random Numbers in Python

The `random` module provides functions for generating random numbers:

  • random(): A random float between 0.0 and 1.0.
  • uniform(a, b)`: A random float between `a` and `b`.
  • randint(a, b)`: A random integer between `a` and `b` (inclusive).

Summation of Numbers

Question 10: Summation of Numbers

Python Code

print(sum(range(1, 102)))  # Output: 5151

Global Variables in Python

Question 11: Creating Global Variables in Python

Declare a variable outside any function to make it global. Use the `global` keyword inside a function to modify a global variable.

Python Code

global_var = 0
def modify_global_var():
    global global_var
    global_var = 10
def printing_global_var():
    print(global_var) 
modify_global_var()
printing_global_var()  # Output: 10

Calculating the Mean of Numbers

Question 12: Calculating the Mean of Numbers

Python Code

n = int(input("Number of elements: "))
l = []
for i in range(n):
    element = int(input("Enter element: "))
    l.append(element)
average = sum(l) / n
print("Average:", round(average, 2)) 
Output (Example)

Number of elements: 4
Enter element: 5
Enter element: 25
Enter element: 74
Enter element: 24
Average: 32.0

Reversing a Number

Question 13: Reversing a Number in Python

This program reverses a given integer.

Python Code

n = int(input("Enter number: "))
reverse = 0
while n > 0:
    digit = n % 10
    reverse = reverse * 10 + digit
    n = n // 10
print("Reversed number:", reverse)
Output (Example)

Enter number: 1234
Reversed number: 4321

List vs. Tuple

Question 14: List vs. Tuple in Python

Key differences:

Feature List Tuple
Mutability Mutable (changeable) Immutable (unchangeable)
Syntax [item1, item2, ...] (item1, item2, ...)
Performance Generally slower Generally faster
Python Code

month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
converting_list = tuple(month)
print(converting_list) # Output: ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
print(type(converting_list)) # Output: <class 'tuple'>

Python: Programming vs. Scripting Language

Question 15: Python: Programming vs. Scripting Language

Python is a general-purpose programming language often used for scripting due to its ease of use and readability. However, it's capable of handling both large-scale software development and smaller scripting tasks.

Interpreted Language

Question 16: Python as an Interpreted Language

Python is an interpreted language, meaning its code is executed line by line by an interpreter, without a separate compilation step. This makes development faster but can result in slightly slower execution compared to compiled languages.

PEP 8

Question 17: PEP 8

PEP 8 is Python's style guide for writing readable and maintainable code. It provides recommendations on formatting, naming conventions, and other stylistic aspects.

Advantages of Python

Question 18: Advantages of Python

Advantages:

  • Readability and ease of use.
  • Large standard library and extensive third-party packages.
  • Cross-platform compatibility.
  • Dynamic typing (no explicit type declarations).
  • Open-source and free to use.

Decorators

Question 19: Decorators in Python

Decorators are a powerful feature in Python used to modify or enhance functions and methods without directly changing their structure. They are identified by the `@` symbol placed before the function or method being decorated. They can be used to add functionality like logging, access control, or instrumentation.

Example Decorator

def my_decorator(func):
    def wrapper():
        print("Before function execution")
        func()
        print("After function execution")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
Output

Before function execution
Hello!
After function execution

List Comprehensions vs. Dictionary Comprehensions

Question 20: List Comprehensions vs. Dictionary Comprehensions

Both are concise ways to create lists and dictionaries. List comprehensions create lists; dictionary comprehensions create dictionaries.

List Comprehension

list_comp = [i for i in range(4)]
print(list_comp)  # Output: [0, 1, 2, 3]
Dictionary Comprehension

dictt = {i: i + 2 for i in range(10)}
print(dictt)  # Output: {0: 2, 1: 3, 2: 4, 3: 5, 4: 6, 5: 7, 6: 8, 7: 9, 8: 10, 9: 11}

Common Python Data Types

Question 21: Common Python Data Types

Python's built-in data types:

  • Numbers (integers, floats, complex numbers)
  • Lists
  • Tuples
  • Strings
  • Sets
  • Dictionaries
  • Booleans

`.py` vs. `.pyc` Files

Question 22: .py vs .pyc Files

`.py` files contain human-readable Python source code. `.pyc` (compiled) files store bytecode (an intermediate representation) that the interpreter uses, potentially speeding up execution.

Local vs. Global Variables

Question 23: Local vs. Global Variables

Differences:

Variable Type Scope
Global Accessible throughout the program
Local Accessible only within the function it's declared in
Python Code

var = 56
def addition():
    var1 = 7
    c = var + var1
    print("Local scope:", var1)  # Output: Local scope: 7
    print("Sum:", c)  # Output: Sum: 63

addition()
print("Global scope:", var)  # Output: Global scope: 56

Lambda Functions

Question 26: Lambda Functions

Lambda functions are small, anonymous functions (functions without a name). They're useful for short, simple operations.

Python Code

sum_ = lambda x, y, z: x + y + z
print("Sum:", sum_(4, 6, 8))  # Output: Sum: 18

`self` in Python

Question 27: `self` in Python

In Python class methods, `self` refers to the instance of the class. It's how you access and modify an object's attributes within its methods.

`break`, `pass`, and `continue`

Question 28: `break`, `pass`, and `continue`

Control flow statements:

  • break: Exits a loop.
  • pass: Does nothing (useful as a placeholder).
  • continue: Skips the current iteration and proceeds to the next.

Randomising List Elements

Question 29: Randomising List Elements

Use `random.shuffle()` to randomize the order of elements in a list.

Python Code

import random
list_ = ["Python", "Interview", "Questions"]
random.shuffle(list_)
print(list_) # Output: (a randomly shuffled list)

Pickling and Unpickling

Question 30: Pickling and Unpickling

Pickling serializes Python objects into a byte stream; unpickling deserializes them back into objects.

Converting Strings to Lowercase

Question 31: Converting Strings to Lowercase

Use the `lower()` method to convert a string to lowercase.

Python Code

string = "TUTORIALSARENA"
print(string.lower())  # Output: tutorialsarena

Multi-line Comments

Question 32: Multi-line Comments

Use a `#` at the beginning of each line to create multi-line comments in Python.

Docstrings

Question 33: Docstrings

Docstrings (documentation strings) are multiline strings used to document Python code. They're enclosed in triple quotes (`"""Docstring"""`).

Python Code

def my_function():
    """This is a docstring."""
    pass
print(my_function.__doc__) # Output: This is a docstring.

Python Arrays vs. Lists

Question 24: Python Arrays vs. Lists

Key difference: Arrays store elements of a single data type; lists can hold elements of mixed data types.

Python Code

import array
array_1 = array.array("i", [3, 6, 2, 7, 9, 5])
list_1 = [4, 'Interview', 7.20]
print(array_1) # Output: array('i', [3, 6, 2, 7, 9, 5])
print(list_1) # Output: [4, 'Interview', 7.2]

try:
    array_2 = array.array("i", [3, 7, 3, "Interview"])
except Exception as e:
    print(e) # Output: 'str' object cannot be interpreted as an integer

`self` in Python

Question 27: `self` in Python

The `self` parameter in Python class methods refers to the instance of the class. It's used to access and modify an object's attributes.

`break`, `pass`, and `continue`

Question 28: `break`, `pass`, `continue`

Control flow statements:

  • break: Terminates a loop.
  • pass: Does nothing (acts as a placeholder).
  • continue: Skips the current iteration and goes to the next.

Shuffling a List

Question 29: Randomising List Elements

The `random.shuffle()` function shuffles the elements of a list in place (modifies the original list).

Python Code

import random
my_list = ["apple", "banana", "cherry"]
random.shuffle(my_list)
print(my_list)  # Output: (a randomly shuffled list)

Pickling and Unpickling

Question 30: Pickling and Unpickling

Pickling serializes Python objects into a byte stream; unpickling reconstructs the objects from that stream. The `pickle` module handles this.

Lowercase Conversion

Question 31: Converting Strings to Lowercase

Use the `lower()` method to convert a string to lowercase.

Python Code

my_string = "Hello World"
print(my_string.lower())  # Output: hello world

Multi-line Comments

Question 32: Multi-line Comments

Use `#` at the beginning of each line for multi-line comments in Python.

Docstrings

Question 33: Docstrings

Docstrings (documentation strings) are used to document Python code. They're multiline strings enclosed in triple quotes (`"""Docstring"""`).

Python Code

def my_function():
    """This is a docstring."""
    pass
print(my_function.__doc__) # Output: This is a docstring.

Multiplication Example

Example: Multiplication in Python

Python Code

a = 39
b = 45
c = a * b
print("Result:", c)  # Output: Result: 1755

Lambda Functions

Question 26: Lambda Functions

Lambda functions are small, anonymous functions (functions without a name). They are defined using the `lambda` keyword. They can take multiple arguments but return only a single expression.

Python Code

sum_ = lambda x, y, z: x + y + z
print("Sum:", sum_(4, 6, 8))  # Output: Sum: 18

`self` in Python

Question 27: `self` in Python

In Python class methods, the `self` parameter refers to the instance of the class. It's used to access and modify an object's attributes.

`break`, `pass`, and `continue`

Question 28: `break`, `pass`, and `continue`

Control flow statements:

  • break: Exits the innermost loop.
  • pass: Does nothing (useful as a placeholder).
  • continue: Skips the current iteration and proceeds to the next.

Randomising a List

Question 29: Randomising a List

The `random.shuffle()` method shuffles a list's elements in place (modifies the original list).

Python Code

import random
my_list = ["apple", "banana", "cherry"]
random.shuffle(my_list)
print(my_list)  # Output: (a randomly shuffled list)

Pickling and Unpickling

Question 30: Pickling and Unpickling

Pickling serializes Python objects into a byte stream that can be stored in a file; unpickling deserializes the byte stream back into Python objects. The `pickle` module handles this process.

Lowercase Conversion

Question 31: Converting to Lowercase

The `lower()` method converts a string to lowercase.

Python Code

my_string = "Hello World"
print(my_string.lower())  # Output: hello world

Multi-line Comments

Question 32: Multi-line Comments

Use `#` at the beginning of each line for multiline comments.

Prime Number Check

Question 41: Prime Number Check

Python Code

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

num = 37
if is_prime(num):
    print(f"{num} is a prime number") # Output: 37 is a prime number
else:
    print(f"{num} is not a prime number")

Palindrome Check

Question 42: Palindrome Check

Check if a sequence is a palindrome (reads the same forwards and backward).

Python Code

def is_palindrome(text):
    processed_text = ''.join(ch for ch in text.lower() if ch.isalnum())
    return processed_text == processed_text[::-1]

sequence = 'abjucujba'
if is_palindrome(sequence):
    print("The sequence is a palindrome") # Output: The sequence is a palindrome
else:
    print("The sequence is not a palindrome")

Extracting N Maximum Indices

Question 43: Extracting N Maximum Indices from a NumPy Array

Use NumPy's `argsort()` method to get indices that would sort the array, then select the last N indices (for the N largest values).

Python Code

import numpy
array = numpy.array([4, 8, 4, 9, 2])
print(array.argsort()[-2:][::-1]) # Output: [3 1]

Calculating Percentiles

Question 44: Calculating Percentiles

NumPy's `percentile()` function calculates percentiles.

Python Code

import numpy
array = numpy.array([3, 6, 1, 6, 5, 2])
percentile = numpy.percentile(array, 45) 
print(percentile)  # Output: 3.5

Binary Number Check

Question 45: Checking for Binary Numbers

Python Code

def is_binary(n):
    return all(c in '01' for c in str(n))

num = 1101001
if is_binary(num):
    print(f"{num} is a binary number")  # Output: 1101001 is a binary number
else:
    print(f"{num} is not a binary number")

Factorial (Iterative)

Question 46: Factorial (Iterative)

Python Code

def factorial_iterative(num):
    if num < 0:
        return "Factorial is not defined for negative numbers"
    elif num == 0:
        return 1
    else:
        fact = 1
        for i in range(1, num + 1):
            fact *= i
        return fact

number = 12
result = factorial_iterative(number)
print(f"The factorial of {number} is {result}") # Output: The factorial of 12 is 479001600

LCM Calculation

Question 47: Computing LCM

Python Code

import math

def compute_lcm(x, y):
    lcm = (x * y) // math.gcd(x, y)
    return lcm

num1 = 24
num2 = 92
print("The LCM of", num1, "and", num2, "is", compute_lcm(num1, num2)) # Output: The LCM of 24 and 92 is 552

Removing Vowels from a String

Question 48: Removing Vowels from a String

Python Code

import re
string = 'tutorialsarena'
result = re.sub(r'[aeiouAEIOU]', '', string)
print("String without vowels:", result)  # Output: String without vowels: Jvtpnt

Array Rotation

Question 49: Rotating an Array

Python Code

def rotate_array(arr, k):
    return arr[-k:] + arr[:-k]

array = [23, 12, 5, 24, 23, 76, 86, 24, 86, 24, 75]
k=2
rotated_array = rotate_array(array,k)
print("Rotated array:", rotated_array) # Output: Rotated array: [75, 24, 86, 24, 23, 76, 86, 23, 12, 5, 24]

Reversing a List

Question 50: Reversing a List in Python

This program iterates through a list in reverse order and prints each element.

Python Code

array = [23, 12, 5, 24, 23, 76, 86, 24, 86, 24, 75]
print("Reverse order of array is ")
for i in range(len(array) - 1, -1, -1):
    print(array[i], end=' ')  # Output: 75 24 86 24 86 76 23 24 5 12 23 
print()

Python `re` Module Methods

Question 34: `split()`, `sub()`, and `subn()` Methods

The Python `re` module provides functions for working with regular expressions.

  • re.split(pattern, string): Splits a string into a list using a regular expression.
  • re.sub(pattern, replacement, string): Replaces substrings matching a pattern.
  • re.subn(pattern, replacement, string): Similar to `sub()`, but returns both the new string and the number of replacements.
Example: re.sub()

import re
text = "The quick brown fox jumps over the lazy fox."
new_text = re.sub(r'fox', 'dog', text)
print(new_text) # Output: The quick brown dog jumps over the lazy dog.

Adding Elements to Python Arrays

Question 35: Adding Items to a Python Array

Methods for adding elements to a Python array:

  • append(x): Adds `x` to the end.
  • extend(iterable): Appends elements from an iterable.
  • insert(i, x): Inserts `x` at index `i`.
Python Code

import array
array = arr.array('d', [1, 2, 3])
array.append(8) 
print(array) # Output: array('d', [1.0, 2.0, 3.0, 8.0])
array.extend([4, 6, 9]) 
print(array) # Output: array('d', [1.0, 2.0, 3.0, 8.0, 4.0, 6.0, 9.0])
array.insert(2, 9) 
print(array) # Output: array('d', [1.0, 2.0, 9.0, 3.0, 8.0, 4.0, 6.0, 9.0])

Removing Elements from Python Arrays

Question 36: Removing Elements from a Python Array

Methods for removing elements:

  • pop([i]): Removes and returns the item at index `i` (default is the last element).
  • remove(x): Removes the first occurrence of `x`.
Python Code

import array
array = arr.array('d', [1, 3, 8, 1, 4, 8, 2, 4])
print(array.pop()) # Output: 4.0
print(array.pop(5)) # Output: 8.0
array.remove(1) 
print(array) # Output: array('d', [3.0, 8.0, 1.0, 4.0, 2.0, 4.0])

Monkey Patching

Question 37: Monkey Patching

Monkey patching is a technique in Python for modifying existing code at runtime. This is often done for testing purposes.

Python Code

class My_Class:
    def f(self):
        print("f()")

import monk
def monkey_f(self):
    print("we are calling monkey_f()")

monk.My_Class.f = monkey_f
object_ = monk.My_Class()
object_.f() # Output: we are calling monkey_f()

Empty Classes

Question 38: Empty Classes in Python

An empty class contains no statements. You create one using the `pass` keyword.

Python Code

class MyClass:
    pass

obj = MyClass()
obj.name = "tutorialsarena"
print("Name:", obj.name) # Output: Name: tutorialsarena

Bubble Sort

Question 39: Bubble Sort in Python

Python Code

def bubble_Sort(array):
    n = len(array)
    for i in range(n-1):
        for j in range(0, n-i-1):
            if array[j] > array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]
    return array

arr = [23, 14, 64, 13, 64, 23, 86]
sorted_arr = bubble_Sort(arr)
print("Sorted array:", sorted_arr)  #Output: Sorted array: [13, 14, 23, 23, 64, 64, 86]

Fibonacci Sequence

Question 40: Fibonacci Sequence

Python Code

def fibonacci(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    else:
        list_fib = [0, 1]
        while len(list_fib) < n:
            next_fib = list_fib[-1] + list_fib[-2]
            list_fib.append(next_fib)
        return list_fib

print(fibonacci(9)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21]