Learn About Python Interview Questions Asked in Top Companies Now

Python has become one of the most popular programming languages today, known for its simplicity and power. Whether you’re a beginner or looking to sharpen your skills, understanding the core concepts of Python is essential. In this article, we’ll dive deep into some of the fundamental topics every Python programmer should know, including lists, arrays, loops, functions, and data handling techniques. We’ll also provide clear, practical examples to help you apply these concepts in real-world scenarios. Let’s unlock the power of Python together!

Table of Contents

    Detailed Python Q&A with Original Explanations and Examples


    1. Does the id() Function Return the Same Value for Variables with Different Values?

    No, the id() function in Python provides the memory address of an object, which is unique for every object. Variables holding different values, like a = 3 and b = 4, will have distinct identities, and hence, their id() values will differ.

    The uniqueness of id() ensures that Python treats a and b as separate entities, even if they might share the same data type.

    2. How to Convert a Multidimensional Array into a One-Dimensional Array?

    The flatten() function from libraries like NumPy converts a multidimensional array into a one-dimensional array. Importantly, the output of this function is a copy of the original array, so any changes made to the flattened array will not impact the original data.

    Here, flatten() ensures that the original array’s structure and values are preserved while creating a new 1D array for further processing.

    3. How Do You Read a File Without Using Pandas?

    To read a file without using Pandas, you can use Python’s built-in functions such as open() or csv module for reading CSV files, or json module for JSON files.

    This reads each row of the CSV file as a list of values.

    4. How to Convert a Series to a DataFrame?

    You can convert a Pandas Series to a DataFrame using the to_frame() method. This converts the Series into a DataFrame, and you can optionally specify the column name.

    5. How Do NaN Values Behave in Comparisons?

    In Python, NaN (Not a Number) is considered to be not equal to any value, including itself. Therefore, when you check NaN == NaN, the result will be False. This is because NaN is used to represent undefined or missing values, and it’s not a standard number, so comparisons do not work as expected.

    To check for NaN values, use the isna() or isnull() method in Pandas.

    6. How to Drop a Column in Python?

    To drop a column from a DataFrame in Pandas, use the drop() function and set the axis parameter to 1 to specify you want to drop columns (not rows). By default, axis=0 drops rows.

    7. Does range(5) Include 5?

    No, range(5) does not include 5 in its output. The range() function generates numbers starting from the first parameter (by default 0) up to, but not including, the second parameter. So, range(5) will generate numbers from 0 to 4.

    The number 5 is not included.

    8. How to Get the Frequency of a Categorical Column?

    To get the frequency (count) of unique values in a categorical column, you can use value_counts() in Pandas. This function returns the counts of each unique value in a column, sorted in descending order by default.

    This shows the frequency of each unique category in the column Category.

    9. What Is the apply() Function in Pandas?

    The apply() function is used in Pandas to apply a function along an axis (rows or columns) of a DataFrame or to a Series. It allows for efficient element-wise operations on entire columns or rows.

    The function passed to apply() is applied to each element in the specified axis (row or column).

    Here, the lambda function squares each value in the numbers column.

    10. How Does the Reverse Function Work?

    The reverse() function is a built-in method in Python that reverses the contents of a list in-place. It does not return a new list but modifies the original list directly.

    It works only with lists and alters the order of elements.

    Notice that the list is reversed directly without creating a new list.

    11. What Is the Difference Between iloc and loc?
    • loc:
      • It is used to access rows and columns by label (i.e., the actual index or column names).
      • Can work with both rows and columns by their labels.

    • iloc:
      • It is used to access rows and columns by their integer position (index).

    Only works with the integer positions of rows and columns, not labels.

    12. Difference Between Lists, Arrays, and Tuples

    In Python, lists, arrays, and tuples are all used to store collections of data, but they have different characteristics:

    Lists are defined using square brackets [].

    List:

    A list is an ordered collection of items, which means the items are stored in a specific sequence.

    Lists are mutable, meaning their elements can be changed after creation.

    A list can store different types of elements, so it is heterogeneous.

    • Array:
      • An array is similar to a list, but it is more efficient for storing large numbers of data items of the same type.
      • Arrays in Python are usually implemented using the array module, or more commonly with numpy arrays.
      • Arrays are mutable and can only store elements of the same type.
      • Arrays are defined using the array module in Python or by importing the numpy library.

    • Tuple:
      • A tuple is also an ordered collection, but it is immutable, meaning its elements cannot be changed once created.
      • Tuples can store any type of element, including mixed types, and are defined using parentheses ().

    13. How to Check if a Number Is Armstrong?

    An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits, each raised to the power of the number of digits. For example, 153 is an Armstrong number because:

    153=13+53+33=153153 = 1^3 + 5^3 + 3^3 = 153

    You can check if a number is an Armstrong number by following these steps:

    If the sum equals the original number, it’s an Armstrong number.

    Calculate the number of digits in the number.

    For each digit, raise it to the power of the number of digits and sum the results.

    In this example, the function checks whether a number is an Armstrong number by summing each digit raised to the power of the total number of digits and comparing it to the original number.

    14. Can Any String Be Converted to an Integer?

    In Python, you can use the int() function to convert a string that represents a number into an integer. However, the string must contain a valid numeric value; otherwise, a ValueError will be raised.

    If the string is not a valid number, the conversion will fail.

    If the string represents a whole number, it will be successfully converted.

    If the string represents a floating-point number, Python will round it down to the nearest integer.

    In the above examples, the int() function is used to convert valid numeric strings to integers. If the string contains a non-numeric value, Python will raise an error, so error handling (e.g., try and except) is often recommended in real-world scenarios.

    15. How to Handle Outliers in Python?

    Yes, you can write a function in Python to impute or remove outliers using statistical methods. One common approach is to use the Interquartile Range (IQR) method, where outliers are defined as values that lie outside the range:

    • Lower bound = Q1 – 1.5 * IQR
    • Upper bound = Q3 + 1.5 * IQR

    You can remove outliers by comparing each value in the dataset to these bounds.

    In this example, the function removes outliers based on the IQR method, keeping only the values within the defined range. The outlier_constant controls how strict the outlier detection is, with 1.5 being the standard multiplier.

    16. What Are the Data Types in Python?

    Python provides several built-in data types that are used to store different kinds of data. These data types can be broadly categorized into the following:

    1. Boolean: Used to store True or False values.
    2. Example: True, False
    3. Set: An unordered collection of unique elements.
    4. Example: {1, 2, 3, 4}
    5. Mapping Type (Dictionary): A collection of key-value pairs.
    6. Example: {'name': 'Alice', 'age': 25}
    7. Sequence Types: Ordered collections of elements:
    1. List: Mutable ordered collection of elements.
      • Example: [1, 2, 3]
    2. Tuple: Immutable ordered collection of elements.
      • Example: (1, 2, 3)
    3. String: Immutable sequence of characters.
      • Example: "Hello, World!"
    4. Numeric Types:
    1. Integer (int): Represents whole numbers.
      • Example: 10
    2. Float: Represents decimal numbers.
      • Example: 3.14
    3. Complex: Represents complex numbers with a real and imaginary part.
      • Example: 3 + 4j

    These data types are the building blocks of Python programs, and understanding them is crucial for manipulating and processing data.

    17. Difference Between append() and extend() Methods

    In Python, both append() and extend() are used to add elements to a list, but they function differently:

    extend(): Adds each element from an iterable (like another list, tuple, or string) to the list. It “extends” the list by adding all elements from the iterable.

    append(): Adds a single element to the end of the list. The element can be any object, including a list, and it is added as a single item.

    In summary:

    • append() adds an individual element to the list.
    • extend() adds multiple elements from an iterable to the list.

    18. How to Import Multiple Excel Sheets into a DataFrame?

    In Python, you can import multiple Excel sheets into a single DataFrame using pandasread_excel() function and concat(). The read_excel() function allows you to specify the sheet_name parameter as None, which loads all sheets from an Excel file. You can then use pd.concat() to combine these sheets into one DataFrame.

    Steps to Import Multiple Excel Sheets:

    1. Use pd.read_excel() to load the Excel file.
    2. Set sheet_name=None to load all sheets.
    3. Use pd.concat() to concatenate all the DataFrames from different sheets into a single DataFrame.

    In this example, sheet_name=None loads all the sheets from the file, and pd.concat() combines them into one DataFrame. The ignore_index=True ensures the index is reset in the concatenated DataFrame.

    19. Call by Value vs. Call by Reference

    Call by Reference: When a function is called by reference, the memory address (or reference) of the argument is passed to the function. Any changes made to the parameter inside the function will affect the original value, as both the parameter and the argument refer to the same memory location.

    Call by Value: When a function is called by value, the actual value of the argument is passed to the function. Any changes made to the parameter inside the function do not affect the original value. This is the default method in many programming languages.

    20. What Is the Difference Between for and while Loops?

    The primary difference between a for loop and a while loop lies in how they control the flow of iterations:

    while loop: The while loop is used when the number of iterations is unknown, and the loop continues until a specified condition becomes False. The condition is checked before each iteration.

    for loop: It is typically used when you know the number of iterations in advance. It iterates over a sequence (like a list, range, or string) and executes a block of code for each item in the sequence.

    21. Difference Between Univariate and Bivariate Analysis
    • Univariate analysis involves examining one variable at a time. It focuses on summarizing and understanding the distribution, central tendency (mean, median), and spread (variance, standard deviation) of a single variable.
    • Bivariate analysis, on the other hand, analyzes the relationship between two variables. It helps in understanding correlations, trends, and dependencies between variables.

    Functions Used in Python for Univariate Analysis:

    • value_counts(): Counts the frequency of unique values in a column.
    • sns.distplot(): Creates a distribution plot of a variable, often used for visualizing the distribution of numerical data.
    • describe(): Provides summary statistics (count, mean, min, max, standard deviation) for numerical variables in a DataFrame.
    • mean(): Computes the mean of a given variable.

    Functions for Bivariate Analysis:

    sns.heatmap(): Visualizes correlation matrices and other relationships between variables as a heatmap.

    sns.boxplot(): Visualizes the relationship between two variables by plotting a boxplot, often used to detect outliers.

    data.corr(): Computes the correlation matrix between multiple variables, indicating the strength of relationships.

    In this example, the univariate analysis looks at the mean of the Age variable, while the bivariate analysis examines the correlation between Age and Income.

    22. How to Check if a Number Is Prime?

    To check whether a number is prime in Python, you can write a function that checks for divisibility. A prime number is a number greater than 1 that is divisible only by 1 and itself. You can iterate through numbers from 2 to the square root of the given number to check if it’s divisible by any number in this range. If no divisors are found, the number is prime.

    Here, the is_prime() function checks if a number is divisible by any integer other than 1 and itself, and returns the appropriate message.

    23. How Can You Change the Index of a DataFrame?

    In Python, you can change the index of a Pandas DataFrame using the set_index() function. This function allows you to set one or more columns as the new index. By default, set_index() returns a new DataFrame with the updated index, but you can modify the original DataFrame in place by setting the inplace=True parameter.

    Key Parameters of set_index():

    verify_integrity: If True, ensures that the new index has no duplicate entries.

    keys: Specifies which column(s) or array-like data should be used as the index.

    drop: When set to True, the column(s) used as the new index are dropped from the DataFrame. Default is True.

    append: If True, the new index is added to the existing index. Default is False.

    inplace: When set to True, changes are made to the original DataFrame.

    In this example, the Name column is set as the new index for the DataFrame, and inplace=True ensures the original DataFrame is updated without needing to assign it to a new variable.

    24. What Is the Use of the inplace Parameter in Pandas?

    The inplace parameter in pandas determines whether a function modifies a DataFrame directly or returns a new one. Setting inplace=True applies changes to the original DataFrame without creating a copy. By default, inplace=False, meaning a new DataFrame is returned, leaving the original unchanged.

    Using inplace=True is memory efficient when working with large datasets but requires caution as it permanently alters the original data structure.

    25. Are Variables mean = 7 and Mean = 7 Considered Equivalent in Python?

    No, Python is a case-sensitive language, meaning it distinguishes between uppercase and lowercase letters. As a result, mean and Mean are treated as entirely different variables.

    The case sensitivity ensures clear variable naming but also requires attention to avoid unintentional conflicts.

    26. What Is the Purpose of the Beautiful Soup Library?

    Beautiful Soup is a powerful Python library designed for web scraping. It enables developers to parse and extract data from HTML and XML documents effortlessly. This is particularly useful for tasks like gathering information from websites for analysis.

    Beautiful Soup simplifies handling nested HTML tags and provides a clean way to access data elements like headers, links, or tables.


    Mastering Python basics is the first step toward becoming a proficient programmer. By understanding core concepts like data types, loops, and functions, you can easily tackle more complex problems and projects. The examples provided in this article are just the beginning – Python’s versatility and rich libraries open up endless possibilities for your coding journey. Keep experimenting, learning, and applying what you’ve learned to continue growing as a Python programmer.

    Top Posts

    Ultimate Data Analyst Interview Guide (0-3 Years)

    Top 40 QA Interview Questions & Answers: The Ultimate 2025 Guide

    Questions Asked In Video Editing Interview

    Deloitte Recent Interview Insights for a Data Analyst Position(0-3 Years)

    Leave a Comment