You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 05 Functions/2 Functions with arbitrary arguments.md
+37-1Lines changed: 37 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,6 +6,8 @@ nav_order: 2
6
6
7
7
# Functions with arbitrary arguments
8
8
9
+
## Defining functions with arbitrary arguments
10
+
9
11
In Python, it is possible to create functions with any number of arguments, not specified in advance. For this purpose, when defining the function, we give a special argument `*args` (an asterisk `*` at the beginning is the important part: the name can be anything, but it is customary to use _args_ and I recommend sticking to this convention):
10
12
11
13
```python
@@ -23,7 +25,7 @@ Similarly, a function can accept any number of arguments given by name. For this
23
25
deffunction2(**kwargs):
24
26
print(kwargs)
25
27
```
26
-
When calling this function, you can pass any number of arguments with any name. Inside the function, the argument `kwargs` will be a **dictionary** containing all the arguments given. For example:
28
+
When calling this function, you can pass any number of arguments with any name. Inside the function, the argument `kwargs` will be a **dictionary** containing all the arguments given. For example:
Similarly like in function definition, you may use `*` and `**` symbols when calling them. See the following example:
87
+
```python
88
+
deffunction(a, b, c):
89
+
print(a, b, c)
90
+
91
+
data = [1, 2, 3]
92
+
function(*data)
93
+
```
94
+
This is equivalent to calling this function as
95
+
```python
96
+
function(1, 2, 3)
97
+
```
98
+
99
+
In general, when calling a function as `function(*sequence)`, the sequence is expanded and its elements are passed as positional parameters. Similarly, `function(**dictionary)` is equivalent to passing the dictionary elements as named parameters. So the function from the example above can be called as
100
+
```python
101
+
params = {'a': 1, 'b': 2, 'c': 3}
102
+
function(**params)
103
+
```
104
+
The keys of the dictionary passes to a function with `**`**must be strings**. In other case, `TypeError` will be raised.
105
+
106
+
The above method of calling function can be used regardless of its definition: it will work for both classical functions and the functions with arbitrary arguments described above.
107
+
108
+
A typical use case is printing all elements of a sequence:
0 commit comments