1. What is the difference between lists and tuples in Python?
Ans:
Lists in Python are mutable, meaning their elements can be modified, added or removed after creation. Tuples, however are immutable and cannot be changed once defined, making lists ideal for dynamic data and tuples suitable for fixed datasets.
2. Explain list comprehension in Python?
Ans:
Using loops and conditions on a single line to create new lists is known as list comprehension. It simplifies code, improves readability and allows efficient list construction compared to traditional looping methods.
3. Why is self used in Python classes?
Ans:
The current instance of a class is denoted by the self keyword. It allows access to the object’s attributes and methods ensuring that each instance can manage and operate on its own data correctly.
4. What are Python generators?
Ans:
Generators are special functions that yield values one at a time instead of returning them all at once. They are memory efficient and useful for handling large datasets or continuous data streams without loading everything into memory.
5. How does Python manage exceptions?
Ans:
Python handles errors using try and except blocks. This mechanism prevents sudden program termination by catching exceptions, allowing developers to provide meaningful error messages and ensure smooth program execution.
6. What are Python modules and packages?
Ans:
One Python file that contains variables, classes, or functions is called a module. A grouping of related modules in a directory is called a package. Both help organize code, promote reusability and simplify the management of large projects.
7. What is the purpose of the pass statement in Python?
Ans:
The pass statement acts as a placeholder when no action is required in a code block. It prevents syntax errors, allowing the program to run smoothly while the logic is left for future implementation.
8. Differentiate between shallow copy and deep copy?
Ans:
A shallow copy duplicates only the top-level structure of an object, so changes to nested elements reflect in both copies. A deep copy, however, creates a complete independent clone of the object, including all nested elements.
9. What are the commonly used built-in data types in Python?
Ans:
Python includes various built-in data types such as integers, floats, strings, lists, tuples, sets, dictionaries and booleans. These types enable developers to store, organize and process different forms of data effectively.
10. How can you convert a list into a dictionary in Python?
Ans:
The elements of a list can be mapped as key-value pairs to create a dictionary. This can be achieved using loops, dictionary comprehensions, or built-in functions, allowing efficient key-based data organization.