[Tutor] "*" operator to unpack argument from a list or tuple

dn PythonList at DancesWithMice.info
Sun Sep 26 03:20:46 EDT 2021


On 26/09/2021 17.56, Manprit Singh wrote:
> Dear Sir,
> In python documentation there is a very good example of * as unpacking
> operator, as given below:
> ls = [3, 6]
> print(sum(range(*ls)))   returns 12 which is a right answer, placing *ls
> inside range()  created a  sequence of numbers as given - 3, 4, 5 and their
> sum is 12.
> 
> See here in this example there is only one iterable being unpacked inside a
> function call . Can we unpack more than one iterable inside function call
> using "*' ?
> 
> Let's assume an example to find addition of all the numbers inside a list,
> tuple & set, using function
> ls = [2, 3]
> tu = (3, 6)
> st = {9, 1}
> The sum will be 24
> 
> The implementation is given below:
> def sumno(*seq):
>     sumno = 0
>     for num in seq:
>         sumno += num
>     return sumno
> 
> ls = [2, 3]
> tu = (3, 6)
> st = {9, 1}
> ans = sumno(*ls, *tu, *st)
> print(ans) returns 24, which is the right answer.
> If you can see, i have unpacked the list, tuple & set inside the function
> call, and i am concluding that all the numbers present inside the list,
> tuple and set will be received by formal parameter seq in the form of
> tuple, and hence the function sumno will return the sum of all numbers .
> 
> I just need to know if i can unpack multiple iterables using * in function
> call or
> not  as done in the previous example ?


Not sure if have understood the question: the code works, ie the
arguments are unpacked and then combined into a (single) tuple, which
becomes parameter seq.

As long as the arguments-provided can be interpreted as *seq, anything
goes...


> A second example to generate a pattern given below:
> 
>          1
>        1 2 1
>      1 2 3 2 1
>    1 2 3 4 3 2 1
>  1 2 3 4 5 4 3 2 1
> 
> For the above pattern, if i write code as given below, is it correct instead
> 
> of that multiple for loop version conventional example taught in schools.
> 
> 
> num = 5
> for row in range(num):
>     print("  "*(num-row-1), *range(1, row+2), *range(row, 0, -1))

To answer your own question: Is the unpacking process a repetition, ie a
form of loop?
-- 
Regards,
=dn


More information about the Tutor mailing list