![]() If we try to destructure a collection with more or fewer values than we provide variables, we end up with a ValueError. You're unlikely to want to perform a destructuring assignment with a set, however, since the order is not guaranteed, and we therefore end up with variables we don't really know the values of. We can also destructure a list, for example, or even a set. With all that in mind, we actually end up destructuring a tuple in the example above, splitting the tuple (5, 11) into its component values, so that we can bind those values to the two variable names. Adding brackets around a single number doesn't turn it into a tuple. However, in this case the brackets are still not part of the tuple syntax. In some instances the brackets are actually necessary, in order to isolate the tuple from the syntax around it, such as when we put a tuple inside a list. In fact, it's the commas which tell Python something is a tuple: we just add brackets for readability in a lot of cases. ![]() One thing that a lot of newer Python programmers in particular don't realise is that parentheses have nothing at all to do with tuples. What if I wrote it like this? x, y = (5, 11) How this works is fairly straightforward, but what's less obvious is that this is an example of destructuring. The values are assigned entirely based on order, so if we switch the variable order, or the order of the values we intend to assign, we will end up with different results. Here we assign the value 5 to x, and 11 to y. We just have to provide the same number of values on both sides of the assignment. Python, like many programming languages, allows us to assign more than one variable at a time on a single line.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |