DEV Community

loading...

Discussion on: 6 Python Tips & Tricks that no One Teaches 🚀🐍

Collapse
codemouse92 profile image
Jason C. McDonald • Edited

Unpacking gets even better than that...

some_iterable = ["I", "have", "no", "idea", "how", "many", "values", "are", "here", "so", "this", "will", "be", "fun!"]
first, second, *_, last = *some_iterable
print(first, second, last)  # I have fun!
Enter fullscreen mode Exit fullscreen mode

You can include one starred name among the names to unpack into. Python will fill in all the others based on position, and then stuff the rest into the starred name.

In this case, I use _ for the name, because I really only intend to throw those away. _ is a completely valid name in Python, but it's conventionally used as a "throw away" name. If you're curious, you can still see what was parked in there in the above code with...

print(_)  # ['no', 'idea', 'how', 'many', 'values', 'are', 'here', 'so', 'this', 'will', 'be']
Enter fullscreen mode Exit fullscreen mode

P.S. Bit of shameless self-promotion, all of the above is in my forthcoming book "Dead Simple Python" (No Starch Press, 2021). So, it isn't quite that "no one" covers this stuff.

Collapse
danidiaztech profile image
Daniel Diaz Author

What such an amazing explanation Jason.🤯
That's exactly why I said the unpack operator deserves an isolated article.

BTW, I'd be glad to read your book.

Collapse
devlorenzo profile image
DevLorenzo

If you want, you can add directly here the link 😉

Collapse
codemouse92 profile image
Jason C. McDonald

Heh, I will once I have one. It'll be this fall, tho.

Forem Open with the Forem app