Python Data Science Jobs & Interviews
20.5K subscribers
191 photos
4 videos
25 files
332 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
Interview question

What is GIL in Python, why is it needed, and how can it be bypassed?

Answer: GIL (Global Interpreter Lock) is a mechanism in the CPython interpreter that ensures only one thread can execute Python bytecode at a time. It was introduced to simplify memory management and ensure thread safety of built-in data structures.

However, due to the GIL, multithreading in Python does not provide true CPU-level parallelism: even if multiple threads are created, they will run sequentially rather than simultaneously, which limits performance in computationally intensive tasks.

This limitation can be bypassed by using modules like multiprocessing, which run separate processes with their own memory and their own GIL. Heavy logic can also be moved to native C extensions or interpreters without a GIL, such as Jython or experimental versions of PyPy.


tags: #interview

@DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
Python Intermediate Level Certification Exam

Instructions:
This exam consists of 50 multiple-choice and code-output questions.
The suggested time for each question is indicated. Total Time: 60 Minutes.
• Choose the single best answer for each question.

---

Section 1: Core Concepts & Data Structures

• (Time: 60s) What will be the output of the following code?
x = 10
def outer_func():
x = 20
def inner_func():
print(x)
inner_func()
outer_func()

a) 10
b) 20
c) Error
d) None

• (Time: 75s) What is the output of this code?
my_list = [1, 2, [3, 4]]
new_list = my_list.copy()
new_list[2][0] = 99
print(my_list)

a) [1, 2, [3, 4]]
b) [1, 2, [99, 4]]
c) [99, 2, [3, 4]]
d) A TypeError occurs.

• (Time: 45s) Which of the following is true about the is and == operators?
a) is compares object identity, == compares value.
b) is compares value, == compares object identity.
c) They are completely interchangeable.
d) is is used for strings and == is for numbers.

• (Time: 60s) What will be the output?
nums = [1, 2, 3, 4, 5, 6]
print(nums[::-2])

a) [6, 4, 2]
b) [1, 3, 5]
c) [2, 4, 6]
d) [5, 3, 1]

• (Time: 75s) What is the most likely output of this code in CPython?
a = 256
b = 256
print(a is b)

c = 257
d = 257
print(c is d)

a) True, True
b) False, False
c) True, False
d) False, True

• (Time: 75s) Which of the following is the primary advantage of a generator expression over a list comprehension?
a) It is always faster.
b) It uses less memory because it evaluates lazily.
c) It can be indexed.
d) It can be used for both reading and writing data.

• (Time: 60s) What is the result of the following set operation?
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print(s1 ^ s2)

a) {3, 4}
b) {1, 2, 5, 6}
c) {1, 2, 3, 4, 5, 6}
d) An error occurs.

• (Time: 90s) What will be printed?
def add_item(item, my_list=[]):
my_list.append(item)
return my_list

print(add_item(1))
print(add_item(2))
print(add_item(3, [10, 20]))

a) [1], [2], [10, 20, 3]
b) [1], [1, 2], [10, 20, 3]
c) [1], [2], [3]
d) [1], [1, 2], [1, 2, 3]

Section 2: Functions & Decorators

• (Time: 60s) What do *args and **kwargs represent in a function definition?
a) Required positional and keyword arguments.
b) Optional positional arguments and required keyword arguments.
c) Pointers to arguments.
d) A variable number of positional and keyword arguments.

• (Time: 75s) What is the output of this code?
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper

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

say_hello()

a) Hello!
b) Before, Hello!, After (each on a new line)
c) Before, After, Hello! (each on a new line)
d) An error occurs.

• (Time: 60s) Which statement about lambda functions is true?
a) They can contain multiple expressions.
b) They cannot have default arguments.
c) They are anonymous functions restricted to a single expression.
d) They must be assigned to a variable.

• (Time: 75s) What will be the output?
data = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, data)))
print(result)

a) [2, 4, 6, 8, 10]
b) [4, 8]
c) [2, 4]
d) A TypeError occurs.
• (Time: 90s) What does the yield keyword do in a function?
a) It terminates the function immediately.
b) It returns a value and raises an exception.
c) It makes the function a generator, pausing its execution and returning a value.
d) It prints a value to the console without returning it.

• (Time: 60s) What will this code print?
def get_multiplier(n):
def multiplier(x):
return x * n
return multiplier

double = get_multiplier(2)
print(double(5))

a) 2
b) 5
c) 10
d) An error occurs.

• (Time: 45s) The concept demonstrated in the question above is called a:
a) Decorator
b) Generator
c) Lambda
d) Closure

Section 3: Object-Oriented Programming (OOP)

• (Time: 60s) What is the main purpose of the __init__ method in a Python class?
a) To destroy an instance of a class.
b) To be the first method run when a script is executed.
c) To initialize the state of a new object when it is created.
d) To define a static method.

• (Time: 75s) What is the difference between a class variable and an instance variable?
a) They are the same.
b) Class variables are shared by all instances; instance variables are unique to each instance.
c) Instance variables are shared by all instances; class variables are unique to each instance.
d) Class variables cannot be modified.

• (Time: 90s) What will be the output of this code?
class Parent:
def speak(self):
print("Parent speaking")

class Child(Parent):
def speak(self):
print("Child speaking")
super().speak()

c = Child()
c.speak()

a) Parent speaking
b) Child speaking
c) Child speaking, Parent speaking (on new lines)
d) Parent speaking, Child speaking (on new lines)

• (Time: 60s) What is the purpose of the super() function in OOP?
a) To call a method from a parent class.
b) To create a superclass.
c) To check if a class is a superclass of another.
d) To delete a parent class.

• (Time: 90s) What does the @staticmethod decorator do?
a) It creates a method that automatically receives the class as the first argument.
b) It converts a method into a function that belongs to the class but doesn't receive any implicit first argument (self or cls).
c) It makes a method private.
d) It allows a method to be called on an instance only.

• (Time: 75s) What is the correct way to define a property that makes an attribute read-only?
a) def get_my_attr(self): ...
b) __my_attr = value
c) @property def my_attr(self): ...
d) static my_attr = value

• (Time: 60s) The principle of a subclass providing a specific implementation of a method that is already provided by its parent class is called:
a) Inheritance
b) Encapsulation
c) Polymorphism
d) Abstraction

• (Time: 90s) What will len(p) return after running this code?
class Playlist:
def __init__(self, songs):
self.songs = songs

def __len__(self):
return len(self.songs)

p = Playlist(['Song A', 'Song B', 'Song C'])

a) An error, len() is not supported.
b) 0
c) 3
d) The memory address of the object.

Section 4: Modules & Standard Library

• (Time: 60s) What is the primary use of the collections.defaultdict?
a) To create a dictionary with a default sorting order.
b) To provide a default value for a key that does not exist, avoiding a KeyError.
c) To create a thread-safe dictionary.
d) To create a dictionary that remembers insertion order (like a standard dict in Python 3.7+).
• (Time: 75s) What will this code print?
from collections import Counter
my_list = ['a', 'b', 'c', 'a', 'b', 'a']
counts = Counter(my_list)
print(counts['a'])

a) 1
b) 2
c) 3
d) ['a', 'a', 'a']

• (Time: 60s) Which module is used for working with dates and times?
a) time
b) date
c) datetime
d) calendar

• (Time: 75s) How do you serialize a Python dictionary d into a JSON formatted string?
a) json.load(d)
b) json.dumps(d)
c) pickle.dumps(d)
d) d.to_json()

• (Time: 90s) What is the output?
import itertools

data = ['A', 'B']
result = list(itertools.permutations(data, 2))
print(result)

a) [('A', 'B')]
b) [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]
c) [('A', 'B'), ('B', 'A')]
d) [('A',), ('B',)]

• (Time: 60s) To check if a file named data.txt exists in the current directory, you would use:
a) os.path.exists('data.txt')
b) os.file.exists('data.txt')
c) sys.path.exists('data.txt')
d) open('data.txt').exists()

Section 5: Error Handling & File I/O

• (Time: 45s) What is the primary purpose of a try...except block?
a) To speed up code execution.
b) To handle exceptions and prevent the program from crashing.
c) To define a new type of error.
d) To test code for syntax errors.

• (Time: 90s) In a try...except...else...finally block, which block is always executed regardless of whether an exception occurred or not?
a) try
b) except
c) else
d) finally

• (Time: 75s) Why is using the with statement (with open(...) as f:) preferred for file handling?
a) It automatically reads the entire file into memory.
b) It provides better performance than a standard try...finally.
c) It automatically closes the file, even if exceptions occur.
d) It automatically creates the file if it doesn't exist.

• (Time: 60s) Which is the best practice for catching exceptions?
a) except:
b) except Exception:
c) except ValueError: (or another specific exception)
d) except Error:

• (Time: 75s) What will happen when this code runs?
try:
print("Start")
result = 10 / 0
print("Middle")
except ZeroDivisionError:
print("Caught error")
else:
print("No error")
finally:
print("Finish")

a) Start, Middle, No error, Finish
b) Start, Caught error, Finish
c) Start, Caught error, No error, Finish
d) The program will crash.

Section 6: Advanced & Miscellaneous

• (Time: 75s) What does a list comprehension like [x for x in range(10) if x % 2 == 0] do?
a) Creates a list of booleans.
b) Creates a list of even numbers from 0 to 9.
c) Creates a list of odd numbers from 0 to 9.
d) Returns a generator object.

• (Time: 90s) What is the output?
my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = {k:v for v, k in my_dict.items()}
print(new_dict[1])

a) a
b) 1
c) b
d) A KeyError.
• (Time: 75s) What is the Global Interpreter Lock (GIL) in CPython?
a) A security feature that locks global variables.
b) A mechanism that allows only one thread to execute Python bytecode at a time.
c) A tool for debugging multi-threaded applications.
d) A memory management utility.

• (Time: 60s) What is the result of *a, b = [1, 2, 3, 4, 5]?
a) a is [1, 2, 3, 4] and b is 5.
b) a is 1 and b is [2, 3, 4, 5].
c) It raises a SyntaxError.
d) a is (1, 2, 3, 4) and b is 5.

• (Time: 90s) To implement a context manager, a class must have which methods?
a) __init__ and __del__
b) __enter__ and __exit__
c) __open__ and __close__
d) __start__ and __stop__

• (Time: 60s) What will the sorted() function do with this input? sorted(['c', 'B', 'a'])
a) ['a', 'B', 'c'] (case-insensitive sort)
b) ['a', 'c', 'B']
c) ['B', 'a', 'c'] (ASCII order)
d) ['c', 'B', 'a'] (no change)

• (Time: 75s) Which of the following correctly finds all numbers greater than 10 in a list called nums in a functional style?
a) filter(lambda x: x > 10, nums)
b) [x for x in nums if x > 10]
c) map(lambda x: x > 10, nums)
d) reduce(lambda x, y: x > 10, nums)

• (Time: 60s) A module that is imported is executed:
a) Every time it is imported.
b) Only the first time it is imported in a program's execution.
c) Never, its functions are just made available.
d) Every time a function from it is called.

• (Time: 90s) What is the purpose of the if __name__ == "__main__": block?
a) It defines the main function of the script.
b) It is required for all Python scripts to run.
c) It allows code to be run only when the file is executed directly as a script, not when imported.
d) It is a comment and has no effect on execution.

• (Time: 60s) Which data type is mutable?
a) tuple
b) str
c) int
d) dict

• (Time: 75s) What is printed?
t = (1, 2, [3, 4])
try:
t[1] = 5
except TypeError:
print("Error 1")
try:
t[2][0] = 9
except TypeError:
print("Error 2")
print(t)

a) Error 1, (1, 2, [9, 4])
b) Error 1, Error 2, (1, 2, [3, 4])
c) Error 1, (1, 2, [3, 4])
d) The code does not print anything.

• (Time: 45s) What is a "virtual environment" in Python used for?
a) To run Python code on a virtual machine.
b) To create an isolated environment for a project with its own dependencies.
c) To test code performance in different environments.
d) A built-in Python IDE.

• (Time: 75s) What is the output?
from collections import namedtuple
Point = namedtuple('Point', 'x y')
p = Point(10, 20)
print(p.x + p[1])

a) A TypeError.
b) 20
c) 30
d) 10

• (Time: 60s) How would you remove the key 'b' from the dictionary d = {'a': 1, 'b': 2}?
a) d.remove('b')
b) d.pop('b')
c) d.delete('b')
d) d.slice('b')

• (Time: 90s) Consider the Walrus Operator :=. What will be the value of count after this loop?
data = [1, 2, 3, 4]
count = 0
while (n := len(data)) > 2:
data.pop()
count += n

a) 0
b) 2
c) 7
d) 9
• (Time: 60s) What does the pass statement do?
a) It terminates the program.
b) It skips the current iteration of a loop.
c) It is a null operation; nothing happens when it executes.
d) It raises a NotImplementedError.

#Python #Certification #Exam #Programming #CodingTest #Intermediate

━━━━━━━━━━━━━━━
By: @DataScienceQ
2
Interview question

What is the difference between asynchrony, multithreading, and multiprocessing?

Answer: Asynchrony works within a single thread and does not block program execution — while some operations wait for I/O completion, others continue running.

Multithreading uses multiple threads within one process that share memory and can run in parallel with coordination among them.

Multiprocessing launches several isolated processes, each with its own address space and resources, allowing true parallelism at the CPU level.

Simply put, asynchrony is efficient for I/O tasks, threads are used for tasks with shared data, and processes are for resource-intensive computations where load distribution across cores is important.


tags: #interview

@DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
1
A generator in Python is a function that returns not a single value, but an iterator object.

Generators differ from regular functions in that they use yield instead of return.
The next value from the iterator is obtained by calling next(generator).

Example:

def multiple_generator(x, n):
    for i in range(1, n + 1):
        yield x * i

multiples_of_5 = multiple_generator(5, 3)

print(next(multiples_of_5))  # 5
print(next(multiples_of_5))  # 10
print(next(multiples_of_5))  # 15


👉  @DataScience4
Please open Telegram to view this post
VIEW IN TELEGRAM
1
The Walrus Operator := (Assignment Expressions)

Introduced in Python 3.8, the "walrus operator" := allows you to assign a value to a variable as part of a larger expression. It's a powerful tool for writing more concise and readable code, especially in while loops and comprehensions.

It solves the common problem where you need to compute a value, check it, and then use it again.

---

#### The Old Way: Repetitive Code

Consider a loop that repeatedly prompts a user for input and stops when the user enters "quit".

# We have to get the input once before the loop,
# and then again inside the loop.
command = input("Enter command: ")

while command != "quit":
print(f"Executing: {command}")
command = input("Enter command: ")

print("Exiting program.")

Notice how input("Enter command: ") is written twice.

---

#### The Pythonic Way: Using the Walrus Operator :=

The walrus operator lets you capture the value and test it in a single, elegant line.

while (command := input("Enter command: ")) != "quit":
print(f"Executing: {command}")

print("Exiting program.")

Here, (command := input(...)) does two things:
• Calls input() and assigns its value to the command variable.
• The entire expression evaluates to that same value, which is then compared to "quit".

This eliminates redundant code, making your logic cleaner and more direct.

#Python #PythonTips #PythonTricks #WalrusOperator #Python3 #CleanCode #Programming #Developer #CodingTips

━━━━━━━━━━━━━━━
By: @DataScienceQ
2
Interview Question

How to view an object's methods?

Answer: To see all methods and attributes associated with a specific object, you can use the dir() function. It takes the object as an argument and returns a list of all attribute and method names of the object.

tags: #interview

@DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
2🔥1
Interview Question

What is the GIL (Global Interpreter Lock) in Python, and how does it impact the execution of multi-threaded programs?

Answer: The Global Interpreter Lock (GIL) is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter at any one time. This means that in a CPython process, only one thread can be executing Python bytecode at any given moment, even on a multi-core processor.

This has a significant impact on performance:

For CPU-bound tasks: Multi-threaded Python programs see no performance gain from multiple CPU cores. If you have a task that performs heavy calculations (e.g., image processing, complex math), creating multiple threads will not make it run faster. The threads will execute sequentially, not in parallel, because they have to take turns acquiring the GIL.

For I/O-bound tasks: The GIL is less of a problem. When a thread is waiting for Input/Output (I/O) operations (like waiting for a network response, reading from a file, or querying a database), it releases the GIL. This allows another thread to run. Therefore, the threading module is still highly effective for tasks that spend most of their time waiting, as it allows for concurrency.

How to achieve true parallelism?

To bypass the GIL and leverage multiple CPU cores for CPU-bound tasks, you must use the multiprocessing module. It creates separate processes, each with its own Python interpreter and memory space, so the GIL of one process does not affect the others.

tags: #Python #Interview #CodingInterview #GIL #Concurrency #Threading #Multiprocessing #SoftwareEngineering

━━━━━━━━━━━━━━━
By: @DataScienceQ
1
Interview question

What objects can be put into a set?

Answer: In Python, a set can only contain hashable (i.e., immutable) objects. This means you can put numbers, strings, tuples (if all their elements are also hashable), boolean values, and other immutable types into a set.

Objects like list, dict, set, and other mutable structures cannot be put in: they do not have a hash function (hash) and will cause a TypeError.

ta
gs: #interview

@DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
1
Python tip:

Use the Path class from the pathlib module to work with file paths cross-platform.

from pathlib import Path

p = Path('/usr/local/bin')


👉  @DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
3
🏆 NumPy Python Tips

📢 Boost your Python skills with NumPy! Learn quick tips for efficient array creation and manipulation to level up your data handling.

Tap to unlock the complete answer and gain instant insight.

━━━━━━━━━━━━━━━
By: @DataScienceQ
1
Tired of missing perfect GOLD entries?
Last week alone: 1,740 pips profit, 10/12 trades won—all shared live in our channel.
Ready to catch the next move? Stay ahead with premium signals & real-time updates—don’t just watch, start profiting!
Join GOLD PIPS SIGNALS before the next trade drops!

#ad InsideAds
1
🌍 Remote Work — India Only 🇮🇳
💰 Earn $800–$2000/month
📆 Weekly payments — card or crypto
🕒 Work 3–4 hours/day
🏠 Fully remote — no office, no experience needed
🎓 Training provided
👉 Indian citizens aged 25+ only
📩 Message our HR manager to apply today!

#ad InsideAds
2
Interview Question

What can be a key in a dictionary?

Answer: Dictionaries in Python are hash tables. Instead of keys, hashes are used in the dictionary. Accordingly, any hashable data type can be a key in the dictionary, which means all immutable data types.

tags: #interview

➡️ @DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
3