Advertisement
nher1625

unpacking with star expressions

Mar 25th, 2015
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. __author__ = 'Work'
  2.  
  3. '''
  4. Star unpacking is similar to list processing features of other functional languages. Lists can be split into head and
  5. tails components.
  6. '''
  7.  
  8. items = [1, 10, 7, 4, 5, 9]
  9. head, *tail = items
  10.  
  11. # Functions can use head and tail splitting to carry out some recursive algorithm.
  12. # Ex:
  13. def summation(items):
  14.     head, *tail = items
  15.     return head + summation(tail) if tail else head
  16.  
  17. items = [2923,239,21,3,5,-12,239,-1233]
  18.  
  19. x = sum(items)
  20. y = summation(items)
  21. print('BIF sum(): ',x, '\n', "summation(): ", y, '\n', 'x == y ? ', x == y)
  22. # If items greater than 1 return the sum of all tail elements and the head. If not return just the head
  23. # (cannot unpack 0 values).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement