Python Reference

Links : Learn     Interview Questions     IDE
            

Python Interview Questions - Page 5

< Previous Page
Question: Can you explain the difference between 'deepcopy()' and 'copy()' functions in Python?
Answer: The 'copy()' function creates a shallow copy of an object, meaning it only copies the top-level structure of the object. If the object contains nested objects (e.g., lists or dictionaries), the references to those nested objects are shared between the original and copied objects.

The 'deepcopy()' function creates a deep copy of an object, meaning it recursively copies the entire object hierarchy, including all nested objects. As a result, the copied object is completely independent of the original object.

Question: How do you remove duplicates from a list in Python?
Answer: You can remove duplicates from a list in Python by converting it to a set (which automatically removes duplicates) and then converting it back to a list.

Question: How do you reverse a list in Python?
Answer: You can reverse a list in Python using either the 'reverse()' method or the slicing syntax. For example:
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
# or
reversed_list = my_list[::-1]
Question: What is the purpose of the 'pass' statement in Python?
Answer: The 'pass' statement in Python is a null operation that does nothing. It is used as a placeholder when a statement is syntactically required but no action needs to be taken.
It is often used as a placeholder for code that will be implemented later.

Question: What are list comprehensions in Python?
Answer: In Python list comprehensions provide a concise way to create lists using a single line of code. They consist of an expression followed by a for loop and optional if clauses. For example:
squares = [x ** 2 for x in range(1, 6)]
Question: What is a set in Python?
Answer: A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove elements from them, but they do not support indexing or slicing operations.

Question: What is a decorator in Python?
Answer: A decorator in Python is a design pattern that allows behavior to be added to functions or methods dynamically. Decorators are implemented using functions that take another function as an argument and return a new function that extends or modifies the behavior of the original function.


< Previous Page