Python Interview Questions and Answers
Question: What is the difference between is
and ==
in Python?
Answer:
In Python, is
and ==
are both used for comparisons, but they serve different purposes and work in different ways.
1. ==
(Equality Operator):
- Purpose: The
==
operator checks if the values of two objects are the same. - It compares the contents or values of the objects, not their identities or memory locations.
- If the values of the two objects are equal,
==
returnsTrue
; otherwise, it returnsFalse
.
Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # Output: True
In this case, a
and b
are two different objects in memory, but they have the same values, so a == b
evaluates to True
.
2. is
(Identity Operator):
- Purpose: The
is
operator checks if two objects refer to the same object in memory (i.e., if they have the same identity). - It compares the memory addresses or identities of the objects, not their values. It returns
True
if both variables point to the exact same object in memory; otherwise, it returnsFalse
.
Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # Output: False
Even though a
and b
have the same values, they are stored in different memory locations, so a is b
evaluates to False
.
However, consider the following:
a = [1, 2, 3]
b = a # b refers to the same object as a
print(a is b) # Output: True
In this case, a
and b
point to the same memory location, so a is b
evaluates to True
.
Summary of the Differences:
==
(Equality): Checks if the values of the two objects are the same.- Compares the content or value of the objects.
is
(Identity): Checks if the two objects refer to the same object in memory (i.e., whether they have the same identity).- Compares the memory addresses (or object references) of the objects.
When to Use Each:
- Use
==
when you want to compare the values of two objects. - Use
is
when you want to check if two variables point to the same object in memory (i.e., when checking for object identity).
Example: is
with Immutable Objects (Singletons)
Python caches certain immutable objects, such as small integers and strings, for performance. In these cases, is
may return True
even for objects that appear to be different, because Python reuses the same object reference for certain immutable values.
x = 1000
y = 1000
print(x == y) # Output: True (because the values are the same)
print(x is y) # Output: False (because they are different objects in memory)
a = 10
b = 10
print(a == b) # Output: True (because the values are the same)
print(a is b) # Output: True (because Python caches small integers like 10)
In the case of small integers (typically integers between -5 and 256), Python will cache and reuse the same object, so is
might return True
even when comparing variables with the same value.
Question: How do you remove duplicates from a list in Python?
Answer:
There are several ways to remove duplicates from a list in Python, each with different characteristics. Below are the most common methods:
1. Using set()
(Efficient but unordered):
The most straightforward way to remove duplicates is by converting the list to a set, because sets do not allow duplicate elements. However, this method does not preserve the order of the original list.
Example:
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))
print(unique_list) # Output: [1, 2, 3, 4, 5] (order is not guaranteed)
- Time Complexity: O(n) for converting a list to a set.
- Space Complexity: O(n).
2. Using a Loop and a New List (Order-preserving):
If you want to preserve the order of the original list, you can use a loop to iterate over the list and add items to a new list only if they haven’t been added yet.
Example:
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = []
for item in my_list:
if item not in unique_list:
unique_list.append(item)
print(unique_list) # Output: [1, 2, 3, 4, 5]
- Time Complexity: O(n^2) in the worst case (because
in
checks membership in the new list, which can take O(n) time for each item). - Space Complexity: O(n).
3. Using a Dictionary (Order-preserving in Python 3.7+):
In Python 3.7 and later, dictionaries preserve the insertion order. You can use a dictionary to remove duplicates while maintaining order by using the list elements as dictionary keys.
Example:
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(dict.fromkeys(my_list))
print(unique_list) # Output: [1, 2, 3, 4, 5]
- Time Complexity: O(n) for creating the dictionary.
- Space Complexity: O(n).
4. Using List Comprehension with a Set (Efficient and Order-preserving):
If you want an efficient solution that preserves the order of the original list, you can use a set to track seen elements and a list comprehension to construct the result.
Example:
my_list = [1, 2, 2, 3, 4, 4, 5]
seen = set()
unique_list = [item for item in my_list if item not in seen and not seen.add(item)]
print(unique_list) # Output: [1, 2, 3, 4, 5]
- Time Complexity: O(n) because checking membership and adding to a set both take O(1) time on average.
- Space Complexity: O(n).
5. Using itertools.groupby()
(Sorted List):
If you want to remove duplicates and ensure the list is ordered, you can first sort the list and then use itertools.groupby()
to group and remove consecutive duplicates. This method requires the list to be sorted before applying groupby()
.
Example:
from itertools import groupby
my_list = [1, 2, 2, 3, 4, 4, 5]
my_list.sort() # Sorting is necessary for groupby
unique_list = [key for key, _ in groupby(my_list)]
print(unique_list) # Output: [1, 2, 3, 4, 5]
- Time Complexity: O(n log n) due to sorting.
- Space Complexity: O(n).
Summary of Methods:
Method | Time Complexity | Space Complexity | Order Preserved |
---|---|---|---|
Using set() | O(n) | O(n) | No |
Using a Loop and a New List | O(n^2) | O(n) | Yes |
Using dict.fromkeys() | O(n) | O(n) | Yes (Python 3.7+) |
Using List Comprehension with a Set | O(n) | O(n) | Yes |
Using itertools.groupby() (Sorted) | O(n log n) | O(n) | Yes (after sorting) |
Recommended Method:
- If you don’t care about order, using
set()
is the fastest and simplest method. - If you need to preserve order, using a list comprehension with a set is the most efficient solution in terms of time complexity.
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.
Tags
- Python
- Python interview questions
- Python decorators
- Global Interpreter Lock
- Memory management
- List vs tuple
- Shallow copy
- Deep copy
- Python generators
- Exception handling
- Lambda function
- Python namespaces
- File modes
- Static method
- Class method
- Serialization
- Python 2 vs Python 3
- Debugging
- Stack and queue in Python
- Serialization in Python
- Python data structures
- Python comprehensions
- Mutable vs immutable
- Python coding interview
- Python fundamentals
- Exception handling in Python