Python / Core Python Fundamentals Interview Questions
What is tuple unpacking and extended unpacking in Python?
Unpacking assigns the individual elements of a sequence to multiple variables in a single statement. The left side must have the same number of names as the sequence has elements, or you get a ValueError.
# Basic unpacking
x, y, z = (10, 20, 30)
first, second = 'AB'
# Swap without a temp variable
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
# Unpacking a function return value
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([5, 2, 8, 1])
print(lo, hi) # 1 8Extended unpacking (Python 3+) uses the starred expression *rest to collect everything that does not fit into the explicit names:
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# Useful for parsing structured payloads
header, *records = open('data.csv').readlines()
# Discard parts you don't need with _
_, important, _ = ('ignore', 'keep this', 'ignore')Unpacking works on any iterable — lists, tuples, strings, generators, files. You can also unpack in a for loop: for x, y in [(1,2),(3,4)]:. Nested unpacking (a, (b, c)) = (1, (2, 3)) works but hurts readability; prefer flatter structures.
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...
