Python / Core Python Fundamentals Interview Questions
What is a Python set and what makes it useful for membership testing?
A set is an unordered collection of unique, hashable objects. Internally it is a hash table, giving O(1) average-case lookup — far faster than scanning a list for large collections. Duplicates are silently dropped on creation.
tags = {'python', 'data', 'python', 'api'} # {'python', 'data', 'api'}
# Membership
print('python' in tags) # True — O(1)
# Add / remove
tags.add('ml')
tags.discard('api') # no error if missing (unlike .remove())
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union {1, 2, 3, 4, 5, 6}
print(a & b) # intersection {3, 4}
print(a - b) # difference {1, 2}
print(a ^ b) # symmetric diff {1, 2, 5, 6}The practical win is deduplication. Converting a list to a set and back is the fastest way to remove duplicates when order does not matter: unique = list(set(my_list)). For order-preserving deduplication use dict.fromkeys(my_list) (dicts maintain insertion order since 3.7).
frozenset is the immutable variant — hashable and usable as a dictionary key or element of another set.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
