Examness

Programming

Python の面接質問

Core language, data model, standard library and idioms.

348 問

  1. 1.

    What is slicing?

    初級

    These are the types of basic Python interview questions for freshers.

    Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string. For this, we use the slicing operator [].

         (1,2,3,4,5)[2:4]
            (3, 4)
         [7,6,8,5,9][2:]
            [8, 5, 9]
         'Hello'[:-1]
            'Hell'
  2. 2.

    Extensible and Integratable

    初級

    Python can be extended with modules written in C, C++, or Rust for performance-critical tasks. It acts as a "glue language," easily integrating with existing legacy codebases and low-level APIs.

  3. 3.

    What are the Runtime Errors?

    初級

    The errors which occurs after starting the execution of the programs are known as runtime errors. Runtime errors can occur because of:

    Invalid Input Invalid Logic Memory issues Hardware failures and so on

    With respect to every reason which causes to runtime error correspoing runtime error representation class is available Runtime error representation classes technically we call as a exception classes. While executing the program if any runtime error is occur corresponding runtime error representation class object is created Creating runtime error representation class object is technically known as a rising exception While executing the program if any exception is raised, then internally python interpreter verify any code is implemented to handle raised exception or not If code is not implemented to handle raised exception then program will be terminated abnormally

    ↥ back to top

  4. 4.

    What are generators in Python?

    初級

    The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function. Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable. We define a function that 'yields' values one by one, and then use a for loop to iterate on it.

        def squares(n):
            i=1
            while(i<=n):
                yield i**2
                i+=1
        for i in squares(7):
            print(i)

    1 4 9 16 25 36 49

    ↥ back to top

  5. 5.

    What is a closure in Python?

    初級

    In Python, a closure is a function object that has access to variables in its enclosing lexical scope, even when the function is called outside that scope. In other words, a closure allows a function to remember and access the values of the variables in the environment where it was created, even if those variables are no longer in scope when the function is called.

    Closures are created when a nested function references a value from its enclosing function. The enclosing function returns the nested function, which maintains a reference to the enclosed value. The enclosed value is stored in the closure, which is attached to the nested function object.

    Here\'s an example of a closure in Python:

    def outer_function(x):
        def inner_function(y):
            return x + y
        return inner_function
    
    closure = outer_function(10)
    result = closure(5)
    print(result)  # Output: 15
    def A(x):
        def B():
            print(x)
        return B
    
    A(7)()

    7

  6. 6.

    How do you calculate the length of a string?

    初級

    This is simple. We call the function len() on the string we want to calculate the length of.

    len('Adi Shakara')

    ↥ back to top

  7. 7.

    What is a namedtuple?

    初級

    A namedtuple will let us access a tuple\'s elements using a name/label. We use the function namedtuple() for this, and import it from collections.

     from collections import namedtuple
     result=namedtuple('result','Physics Chemistry Maths') #format
     Ramayan=result(Physics=86,Chemistry=95,Maths=86) #declaring the tuple
     Ramayan.Chemistry

    95

    As you can see, it let us access the marks in Chemistry using the Chemistry attribute of object Ramayan.

  8. 8.

    In Python what are iterators?

    初級

    In Python, iterators are used to iterate a group of elements, containers like list.

  9. 9.

    What is List Comprehensions feature of Python used for?

    初級

    List comprehensions help to create and manage lists in a simpler and clearer way than using map(), filter() and lambda. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses.

    ↥ back to top

  10. 10.

    What is the size of an integer in Python?

    初級

    Unlike C/Java where int is fixed at 4 bytes, Python integers have arbitrary precision — they grow as needed. CPython uses a PyLongObject struct. A small integer takes 28 bytes minimum (sys.getsizeof(0)), and size grows with magnitude. CPython also maintains a small integer cache for values in [-5, 256], reusing the same object rather than allocating new ones.

    import sys
    
    print(sys.getsizeof(0))        # 24 bytes (Python 3.11+)
    print(sys.getsizeof(1))        # 28 bytes
    print(sys.getsizeof(2**30))    # 32 bytes
    print(sys.getsizeof(2**60))    # 36 bytes
    print(sys.getsizeof(2**90))    # 40 bytes — grows with digit count
    
    # Small integer cache demo
    a = 256
    b = 256
    print(a is b)   # True — same cached object
    
    a = 257
    b = 257
    print(a is b)   # False — different objects (outside cache range)
    
    # Python handles arbitrarily large integers natively
    big = 2 ** 10000
    print(type(big))  # <class 'int'>

    Use Case: Cryptographic libraries (e.g., RSA key generation) rely on Python\'s arbitrary-precision integers to perform modular exponentiation with 2048-bit or 4096-bit numbers natively, without any overflow concerns.

    ↥ back to top

  11. 11.

    Versatile Application Domains

    初級

    Python is a "general-purpose" language. It dominates diverse fields including Artificial Intelligence, scientific computing, backend web development, and DevOps scripting.

  12. 12.

    What is TkInter?

    初級

    TkInter is Python library. It is a toolkit for GUI development. It provides support for various GUI tools or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors, etc.

  13. 13.

    What is a namespace in Python?

    初級

    In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

    A namespace is a collection of names. It maps names to corresponding objects. When different namespaces contain objects with the same names, this avoids any name collisions. Internally, a namespace is implemented as a Python dictionary.

    On starting the interpreter, it creates a namespace for as long as we don\'t exit. We have local namespaces, global namespaces, and a built-in namespace.

    ↥ back to top

  14. 14.

    What is the concatenation?

    初級

    This is very basic Python Interview Question, try not to make any mistake in this.

    Concatenation is joining two sequences. We use the + operator for this.

    '32'+'32' '3232'

    [1,2,3]+[4,5,6] [1, 2, 3, 4, 5, 6]

    (2,3)+(4) Traceback (most recent call last): File " ", line 1, in (2,3)+(4) TypeError: can only concatenate tuple (not "int") to tuple

    Here, 4 is considered an int. Let\'s do this again.

    (2,3)+(4,) # (obj,) is way to declare single empty (2, 3, 4)

    ↥ back to top

  15. 15.

    What is the use of enumerate() in Python?

    初級

    enumerate() wraps an iterable and yields (index, value) pairs, eliminating the need for a manual counter variable. It is O(1) memory (returns a lazy iterator) and supports a start parameter to control the starting index.

    fruits = ["apple", "banana", "cherry", "date"]
    
    # Without enumerate — error-prone manual counter
    for i in range(len(fruits)):
        print(i, fruits[i])
    
    # With enumerate — Pythonic, cleaner
    for i, fruit in enumerate(fruits):
        print(i, fruit)
    # 0 apple
    # 1 banana
    # 2 cherry
    # 3 date
    
    # Custom start index
    for i, fruit in enumerate(fruits, start=1):
        print(f"{i}. {fruit}")
    # 1. apple
    # 2. banana
    # 3. cherry
    # 4. date
    
    # Building indexed structures
    index_map = {fruit: i for i, fruit in enumerate(fruits)}
    print(index_map)   # {'apple': 0, 'banana': 1, 'cherry': 2, 'date': 3}
    
    # Tracking position while modifying (safe pattern)
    data = [3, -1, 4, -1, 5, 9, -2]
    for i, val in enumerate(data):
        if val < 0:
            data[i] = 0   # replace negatives in-place using index
    
    print(data)   # [3, 0, 4, 0, 5, 9, 0]
    
    # Works with any iterable
    for line_no, line in enumerate(open("README.md"), start=1):
        if "TODO" in line:
            print(f"Line {line_no}: {line.rstrip()}")
            break

    Use Case: A CSV validator uses enumerate(rows, start=2) (header is row 1) to report validation errors with their exact spreadsheet line number: "Row 47: missing required field 'email'" — without any manual counter.

    ↥ back to top

  16. 16.

    What is a decorator? How do I define my own?

    初級

    Ans. A decorator is a function that adds functionality to another function without modifying it. It wraps another function to add functionality to it. A Python decorator is a specific change that we make in Python syntax to alter functions easily.

    def decor(func):
        def wrap():
            print("$$$$$$$$$$$$$$$$$")
            func()
                print("$$$$$$$$$$$$$$$$$")
        return wrap
    
    @decor
    def sayhi():
        print("Hi")
    
    sayhi()

    $$$$$$$$$$$$$$$$$ Hi $$$$$$$$$$$$$$$$$

    Decorators are an example of metaprogramming, where one part of the code tries to change another. For more on decorators, read Python Decorators.

    ↥ back to top

  17. 17.

    Simple and Readable Syntax

    初級

    Python uses significant indentation rather than curly braces or keywords to define code blocks. Its syntax mimics natural English, adhering to the PEP 8 style guide to ensure high maintainability and readability.

  18. 18.

    What are tools for data ingestion?

    初級

    Data ingestion tools move data from sources into storage/processing systems. They fall into several categories:

    CategoryToolsBest For
    Message Queues / StreamingApache Kafka, AWS Kinesis, Azure Event Hubs, Google Pub/SubReal-time event streams
    Batch ETL / PipelineApache Airflow, Azure Data Factory, AWS Glue, dbtScheduled batch ingestion
    Log / Event CollectionLogstash (ELK), Fluentd, Filebeat, VectorLog aggregation
    Change Data Capture (CDC)Debezium, AWS DMS, StriimDB replication / CDC
    File TransferApache NiFi, Airbyte, FivetranFile-based & API connectors
    Python Librarieskafka-python, boto3, azure-eventhub, apache-beamCustom pipelines
    # Example: Producing messages to Apache Kafka using kafka-python
    from kafka import KafkaProducer
    import json
    
    producer = KafkaProducer(
        bootstrap_servers=["localhost:9092"],
        value_serializer=lambda v: json.dumps(v).encode("utf-8"),
        acks="all",           # strongest durability guarantee
        retries=3,
        max_in_flight_requests_per_connection=1,  # ensure ordering
    )
    
    event = {"user_id": "u123", "action": "purchase", "amount": 49.99}
    future = producer.send("user-events", value=event, key=b"u123")
    record_metadata = future.get(timeout=10)
    print(f"Sent to {record_metadata.topic}:{record_metadata.partition} @ {record_metadata.offset}")
    producer.flush()
    producer.close()

    Use Case: A ride-sharing platform ingests 2M GPS location updates per minute using Apache Kafka as the ingestion backbone, with Kafka Streams for real-time ETA computation and a Spark Structured Streaming job writing aggregated trip data to Delta Lake every 30 seconds.

    ↥ back to top

  19. 19.

    What is the built-in function used in Python to iterate over a sequence of numbers?

    初級

    Syntax: range(start,end,step count)

    Ex:

    a = range(1,10,2)
    print (a)

    Output: [1, 3, 5, 7, 9]

    If using to iterate

    for i in range(1,10):
        print (i)

    Output:

    > 1 2 3 4 5 6 7 8 9

    ↥ back to top

  20. 20.

    What is try Block?

    初級

    A block which is preceded by the try keyword is known as a try block Syntax: try{ //statements that may cause an exception }

    The statements which causes to run time errors and other statements which depends on the execution of run time errors statements are recommended to represent in try block While executing try block statement if any exception is raised then immediately try block identifies that exception, receive that exception and forward that exception to except block without executing remaining statements to try block.

    ↥ back to top