| Start |
|---|
| Destructuring assignment In assignments, you can split an Iterable into values using the "unpacking" syntax: Destructuring as valuesIf you try to unpack more than the length of the iterable, you'll get an error: Destructuring as a listYou can unpack a list of unknown length using the following syntax: Here, we extract the first value as a scalar, and the other values as a list: Which is equivalent to: It also works with multiple elements or elements form the end of the list: Ignoring values in destructuring assignmentsIf you're only interested in a given value, you can use Ignoring lists in destructuring assignmentsFinally, you can ignore many values using the which is not really interesting, as you could using indexing on the list instead. Where it gets nice is to keep first and last values in one assignment: or extract several values at once: |
| Packing function arguments In functions, you can define a number of mandatory arguments: which will make the function callable only when the three arguments are given: and you can define the arguments as optional, by using default values: so you can call the function in many different ways, like: But you can also use the destructuring syntax to pack arguments up, so you can assign variables using a Packing a list of argumentsConsider you have a list of values You can call the function with the list of values as an argument using the But if you do not provide a list which length matches the number of arguments: Packing keyword argumentsNow, you can also pack arguments using a dictionary. You can use the when the function only has positional arguments (the ones without default values) you need the dictionary to be contain of all the expected parameters, and have no extra parameter, or you'll get an error: For functions that have optional arguments, you can pack the arguments as a dictionary the same way: But there you can omit values, as they will be replaced with the defaults: And the same as before, you cannot give extra values that are not existing parameters: In real world usage, functions can have both positional and optional arguments, and it works the same: you can call the function with just an iterable: or with just a dictionary: or you can use both in the same call: Beware though that you cannot provide multiple values for the same argument: |
| Unpacking function arguments When you want to create a function that can accept any number of arguments, and not enforce the position or the name of the argument at "compile" time, it's possible and here's how: The If you look at enough Python code, you'll quickly discover that it is widely being used when passing arguments over to another function. For example if you want to extend the string class: |
Read Article
https://develop.horje.com/learn/1434/reference