some_iterable=["I","have","no","idea","how","many","values","are","here","so","this","will","be","fun!"]first,second,*_,last=*some_iterableprint(first,second,last)# I have fun!
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...
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.
Software developer, Technical writer, and long-life learner. I enjoy creating software from scratch and sharing knowledge with stunning technical articles. Visit my website -> https://danidiaztech.com
Hello World 👋🏻I'm a young man working to be a full stack developer. My goal is to create a programming community for exchanging ideas. Send weekly newsletter! Thx for 160k view❤
Unpacking gets even better than that...
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...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.
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.
If you want, you can add directly here the link 😉
Heh, I will once I have one. It'll be this fall, tho.