Unpacking: The Biggest Flex 💪


Unpacking: The Biggest Flex 💪





Trying to assign list items to variables? If you're doing a = my_list[0], please log off. We have to talk about unpacking. It's the biggest flex in Python. 😤

Behold:

my_list = ["Icon", "Legend", "Star"]
first, second, third = my_list
print(first)  # Output: "Icon" 💃

No indexes. Just pure, clean assignment. It's so satisfying.

But what if the list is longer? Use the star * to collect the rest. It's the "and friends" of coding.

first, second, *the_rest = [1, 2, 3, 4, 5]
print(first)      # 1
print(second)     # 2
print(the_rest)   # [3, 4, 5] 👯‍♀️

You can even use it to ignore values. Want just the first and last?

first, *_, last = [1, 2, 3, 4, 5]
print(first)  # 1
print(last)   # 5
# The *_ ate the middle. No drama. 🍝

Unpacking is that girl. Use it to make your code look expensive. 💎


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like Genius.

Comments

Popular posts from this blog

The New ChatGPT Reason Feature: What It Is and Why You Should Use It

Insight: The Great Minimal OS Showdown—DietPi vs Raspberry Pi OS Lite

Raspberry Pi Connect vs. RealVNC: A Comprehensive Comparison