Some Python Utilities

Python Utilities
Author

Nipun Batra

Published

January 17, 2023

Function Argument Unpacking

Reference: https://www.youtube.com/watch?v=YWY4BZi_o28

def print_vec(x, y, z):
    print(f"[{x} \n{y} \n{z}]")
print_vec(1, 2, 3)
[1 
2 
3]
tuple_vec = (1, 0, 1)
#print_vec(tuple_vec)
print_vec(tuple_vec[0], tuple_vec[1], tuple_vec[2])
[1 
0 
1]
list_vec = [1, 0, 1]

print_vec(tuple_vec[0], tuple_vec[1], tuple_vec[2])
print("*"*20)
print_vec(*tuple_vec)
print("*"*20)

print_vec(*list_vec)
[1 
0 
1]
********************
[1 
0 
1]
********************
[1 
0 
1]
dictionary_vec = {"x": 1, "y": 0, "z": 1}
print_vec(**dictionary_vec)
[1 
0 
1]
dictionary_vec = {"a": 1, "b": 0, "c":1}
print_vec(**dictionary_vec)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/nipun/git/ml2023/notebooks/posts/python-utils.ipynb Cell 8 in <cell line: 2>()
      <a href='vscode-notebook-cell:/Users/nipun/git/ml2023/notebooks/posts/python-utils.ipynb#W6sZmlsZQ%3D%3D?line=0'>1</a> dictionary_vec = {"a": 1, "b": 0, "c":1}
----> <a href='vscode-notebook-cell:/Users/nipun/git/ml2023/notebooks/posts/python-utils.ipynb#W6sZmlsZQ%3D%3D?line=1'>2</a> print_vec(**dictionary_vec)

TypeError: print_vec() got an unexpected keyword argument 'a'
print(*dictionary_vec)
a b c

Zip

list(zip([1, 2, 3], ['a', 'b', 'c'], [7, 8, 9]))
[(1, 'a', 7), (2, 'b', 8), (3, 'c', 9)]

Itertools Product

import itertools
list(itertools.product([1, 2], ['a', 'b', 'c'], [7, 8, 9]))
[(1, 'a', 7),
 (1, 'a', 8),
 (1, 'a', 9),
 (1, 'b', 7),
 (1, 'b', 8),
 (1, 'b', 9),
 (1, 'c', 7),
 (1, 'c', 8),
 (1, 'c', 9),
 (2, 'a', 7),
 (2, 'a', 8),
 (2, 'a', 9),
 (2, 'b', 7),
 (2, 'b', 8),
 (2, 'b', 9),
 (2, 'c', 7),
 (2, 'c', 8),
 (2, 'c', 9)]