The right-hand side of the assignment may be any iterable object. The sequence you unpack must have exactly as many items as the targets you list on the left of the sign otherwise, Python raises an exception when the assignment is performed. The starred variable may also be placed first, and it will always contain a list. Suppose we have an tuple or a sequence of N elements like below: mySequence 'FBA', 20, 3000.30, (18, 12, 2000) I want to unpack all of the sequential data into different variables, but I want to do that using a simple assignment operation. For example, a, b, rest* = will result in rest gathering whatever remains after assigning values to a and b. Unpacking a sequence into separate variables is a simple task if you use Python for it as well. ■Note Python 3.0 has another unpacking feature: you can use the star operator (*), just as in function argument lists (see Chapter 6). The sequence you unpack must have exactly as many items as the targets you list on the left of the = sign otherwise Python raises an exception when the assignment is performed:įile "", line 1, in ValueError: need more than 2 values to unpack > x, y, z = 1, 2, 3, 4 Traceback (most recent call last):įile "", line 1, in ValueError: too many values to unpack This allows functions to return more than one value, packed as a tuple, easily accessible through a single assignment. Then you can unpack the returned tuple directly into two variables: You can then use the popitem method, which does just that, returning the pair as a tuple. Let's say that you want to retrieve (and remove) an arbitrary key-value pair from a dictionary. This is particularly useful when a function or method returns a tuple (or other sequence or iterable object). I have a sequence (or an arbitrary iterable object) of values, and I unpack it into a sequence of variables. You can perform several different assignments simultaneously:ĭoesn't sound useful? Well, you can use it to switch the contents of two (or more) variables:Īctually, what I'm doing here is called sequence unpacking (or iterable unpacking). You've seen quite a few examples of assignments, both for variables and for parts of data structures (such as positions and slices in a list, or slots in a dictionary), but there is more.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |