Data Scientist Python Interview Questions

author image Hirely
at 05 Jan, 2025

Question: What are Python’s file modes?

Answer:

In Python, when working with files, you need to specify the mode in which you want to open a file. The mode determines how you can interact with the file (whether you can read, write, append, etc.). These modes are specified as a string parameter in the open() function.

Here are the common file modes in Python:


1. Read Mode ('r'):

  • Opens the file for reading.
  • If the file does not exist, it raises a FileNotFoundError.
  • The file pointer is positioned at the beginning of the file.

Example:

file = open('example.txt', 'r')
content = file.read()
file.close()

2. Write Mode ('w'):

  • Opens the file for writing.
  • If the file already exists, it overwrites the file content.
  • If the file does not exist, it creates a new file.
  • The file pointer is positioned at the beginning of the file.

Example:

file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()

3. Append Mode ('a'):

  • Opens the file for appending.
  • If the file already exists, the content is added to the end of the file.
  • If the file does not exist, it creates a new file.
  • The file pointer is positioned at the end of the file.

Example:

file = open('example.txt', 'a')
file.write('\nThis is an appended line.')
file.close()

4. Read-Write Mode ('r+'):

  • Opens the file for reading and writing.
  • The file must already exist; otherwise, it raises a FileNotFoundError.
  • The file pointer is positioned at the beginning of the file.

Example:

file = open('example.txt', 'r+')
content = file.read()
file.write('Updated content')
file.close()

5. Write-Read Mode ('w+'):

  • Opens the file for reading and writing.
  • If the file already exists, it overwrites the entire file.
  • If the file does not exist, it creates a new file.
  • The file pointer is positioned at the beginning of the file.

Example:

file = open('example.txt', 'w+')
file.write('New content')
file.seek(0)  # Go back to the beginning of the file to read it
content = file.read()
file.close()

6. Append-Read Mode ('a+'):

  • Opens the file for reading and appending.
  • If the file already exists, it appends new content to the end without overwriting.
  • If the file does not exist, it creates a new file.
  • The file pointer is positioned at the end of the file for appending, but you can use seek() to move to any part of the file for reading.

Example:

file = open('example.txt', 'a+')
file.write('\nAppending new data')
file.seek(0)  # Go to the beginning of the file to read
content = file.read()
file.close()

7. Binary Mode ('b'):

  • Binary mode is added to other modes ('r', 'w', 'a', etc.) to handle binary files (e.g., images, videos).
  • In binary mode, the data is read and written as bytes instead of text.

Common modes with binary option:

  • Read binary: 'rb'
  • Write binary: 'wb'
  • Append binary: 'ab'
  • Read and write binary: 'r+b', 'w+b', 'a+b'

Example (Reading a binary file):

file = open('example.png', 'rb')
content = file.read()
file.close()

8. Universal Newline Mode ('U') (Deprecated in Python 3.x):

  • In earlier versions of Python (before Python 3.x), 'U' was used to handle universal newlines and automatically convert different newline characters (\n, \r\n, \r) to the appropriate format for the operating system.
  • This mode is deprecated in Python 3.x and is automatically handled by the open() function.

9. Text Mode ('t') (Default):

  • The default mode is text mode ('t'), which is used for reading or writing text files.
  • In this mode, the file content is handled as strings.
  • This mode is implicitly assumed if 't' is not explicitly specified (e.g., open('file.txt', 'r')).

Combining Modes:

You can combine different modes to control how a file is opened. For example:

  • 'r+b': Opens the file for reading and writing in binary mode.
  • 'w+t': Opens the file for writing in text mode (this is the default).

Example:

file = open('example.txt', 'r+b')  # Reading and writing in binary mode

Summary of Common File Modes:

ModeDescription
'r'Read (file must exist)
'w'Write (file is overwritten, or created if it doesn’t exist)
'a'Append (adds to the end of the file, creates the file if it doesn’t exist)
'r+'Read and write (file must exist)
'w+'Write and read (overwrites file, or creates new)
'a+'Append and read (creates the file if it doesn’t exist)
'b'Binary mode (used with other modes, e.g., 'rb', 'wb')
't'Text mode (default, used to handle text files)

Conclusion:

When opening a file in Python, the mode you choose determines how the file is accessed. Understanding the different modes allows you to control how Python interacts with files and ensures that you can handle files according to your needs (whether reading, writing, appending, or dealing with binary data).

Question: What is a lambda function in Python?

Answer:

A lambda function in Python is a small anonymous function defined using the lambda keyword. Unlike regular functions defined using the def keyword, lambda functions are used for creating short, throwaway functions in a concise way. Lambda functions can have any number of input parameters but only one expression, which is evaluated and returned automatically.


Syntax:

lambda arguments: expression
  • arguments: A comma-separated list of parameters (like in regular functions).
  • expression: A single expression that is evaluated and returned.

Key Characteristics of Lambda Functions:

  • They can take multiple arguments.
  • They have a single expression, and the result of that expression is automatically returned.
  • They are often used where a small function is needed temporarily, usually as arguments to higher-order functions (such as map(), filter(), or sorted()).

Example:

# A simple lambda function that adds 10 to the input value
add_ten = lambda x: x + 10

print(add_ten(5))  # Output: 15

In this example:

  • The lambda function takes one argument (x) and returns x + 10.

Lambda Function with Multiple Arguments:

# A lambda function that multiplies two numbers
multiply = lambda x, y: x * y

print(multiply(3, 4))  # Output: 12

Here, the lambda function takes two arguments (x and y) and returns their product.


Common Use Cases for Lambda Functions:

1. Sorting with Custom Key:

Lambda functions are often used with the sorted() function to define custom sorting behavior.

# Sorting a list of tuples based on the second element
data = [(1, 2), (3, 1), (5, 0)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)  # Output: [(5, 0), (3, 1), (1, 2)]

In this example, the list of tuples is sorted based on the second element of each tuple.

2. Using with map(), filter(), and reduce():

Lambda functions are often used as arguments to functions like map(), filter(), and reduce().

  • map(): Applies a function to all items in an iterable.

    numbers = [1, 2, 3, 4]
    squared = list(map(lambda x: x ** 2, numbers))
    print(squared)  # Output: [1, 4, 9, 16]
  • filter(): Filters the elements based on a condition.

    numbers = [1, 2, 3, 4, 5, 6]
    even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
    print(even_numbers)  # Output: [2, 4, 6]
  • reduce(): Applies a function cumulatively to the items in an iterable.

    from functools import reduce
    numbers = [1, 2, 3, 4]
    product = reduce(lambda x, y: x * y, numbers)
    print(product)  # Output: 24

Lambda Function vs Regular Function:

  • Lambda:
    • Concise syntax.
    • Can only have a single expression.
    • Primarily used for short-term use cases or as arguments to higher-order functions.
  • Regular Function (def):
    • Can have multiple expressions.
    • Typically used for defining reusable functions.

Example:

# Regular function
def add(x, y):
    return x + y

# Lambda function
add_lambda = lambda x, y: x + y

Both of the above functions perform the same task, but the lambda function is more concise.


When to Use Lambda Functions:

  • Short-term functions: When you need a simple function for a short period and don’t want to formally define it using def.
  • Higher-order functions: When passing a function as an argument to functions like map(), filter(), or sorted().

Conclusion:

Lambda functions in Python are a powerful feature for writing small, anonymous functions that can be used on the fly. They are widely used in situations where a short, simple function is required, particularly with functions like map(), filter(), and sorted().

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as Python interview questions, Python interview experiences, and details about various Python job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now