7/22/2023 0 Comments Python unpacking sequenceIf you’d like you might even decide to adopt a convention of always using a list-like syntax when unpacking list-like structures (frequently the case when using * in multiple assignment): When you’re unpacking structures that often hold lots of values (like lists) and structures that often hold a very specific number of values (like tuples) you may decide that your code appears more semantically accurate if you use a list-like syntax when unpacking those list-like structures. We’re limiting the list we’re getting back to just a single item. The most_common method on Counter objects allows us to limit the length of the list returned to us. We’re using a Counter object from the collections module here. When I see this, I also think I bet we’re unpacking a single-item list. The list-syntax in our assignment makes it more clear that we’re unpacking a one-item iterable and then unpacking that single item into value and times_seen variables. Python’s multiple assignment looks like this:ĭef most_common ( items ): = Counter ( items ). They’re all just different words for the same thing. I’ll be using the words multiple assignment, tuple unpacking, and iterable unpacking interchangeably in this article. If you’re on an older version of Python, you’ll need to mentally translate those to use the string format method. Note that in this article I will be using f-strings which are a Python 3.6+ feature. In this article we’ll see what multiple assignment is, we’ll take a look at common uses of multiple assignment, and then we’ll look at a few uses for multiple assignment that are often overlooked. This feature often seems simple after you’ve learned about it, but it can be tricky to recall multiple assignment when you need it most. Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign multiple variables at the same time in one line of code. Whether I’m teaching new Pythonistas or long-time Python programmers, I frequently find that Python programmers underutilize multiple assignment.
0 Comments
Leave a Reply. |