Monday, 30 April 2018

Splat Operator:

'*' is the splat operator in python
spalt operator is also known as scatter operator.
Splat operator is used to unpack a packed data type like list.

Generally, splat operator is used in methods (function) which can have any number of elements as input.

For example:
average method:

>>> def average(*elements):
...     s = 0
...     for e in elements:
...         s += e
...     print("Average :", s/len(elements))
...
>>> average(1,2,3)
Average : 2.0
>>> average(1,2,3,6,8,0)
Average : 3.3333333333333335


Note : Spalts are also used in retrieving elements from zipped objects.

For example:
>>> zip_object = zip(['one', 'two', 'three'], [1,2,3])
>>> zip_object
<zip object at 0x7f654145ce88>
>>> unzipped_list = [*zip_object]
>>> unzipped_list
[('one', 1), ('two', 2), ('three', 3)]

In Python3,
splat operator has more use in unpacking and assigning.

>>> a, *b, c = range(10)
>>> print(a, b, c)
0 [1, 2, 3, 4, 5, 6, 7, 8] 9

This property of unpacking is useful for handling multiple number of return parameters where all of them may/not be used.

Also in some revisions, user is also unaware of number of return parameters. In that case, splat is very useful.

>>> def unpredictable(n):
...     '''returns any number of random nuumbers upto n'''
...     return [random(1, n) for i in range(random(1, n))]
...
>>> a, b, *d = unpredictable(10)
>>> a
1
>>> b
6
>>> d
[3, 3, 5, 4, 7, 9]


No comments:

Post a Comment

Memoization : Memoization is a technique for remembering the results that incur huge costs to running time to the algorithm. Memoizati...