3

I have a function that takes multiple arguments of tuples and process it accordingly. I was wondering if I can pass the arguments in a for-loop. For example:

def func(*args):
   for a in args:
      print(f'first {a[0]} then {a[1]} last {a[2]}')

Then I would call the function as

func(('is', 'this', 'idk'), (1,2,3), ('a', '3', 2))

My question is if there is a way that I could modify the function calling in a loop without changing the function definition itself:

func((i, i, i) for i in 'yes'))

such that it will print:

first y then y last y
first e then e last e
first s then s last s
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
JediBig
  • 51
  • 1
  • 4

2 Answers2

4

Yes, with a generator expression and * argument unpacking in the call:

func(*((i, i, i) for i in 'yes'))

which could also be written with the generator expression assigned to a variable first:

args = ((i, i, i) for i in 'yes')
func(*args)

Demo:

>>> func(*((i, i, i) for i in 'yes'))
first y then y last y
first e then e last e
first s then s last s
>>> args = ((i, i, i) for i in 'yes')
>>> func(*args)
first y then y last y
first e then e last e
first s then s last s
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Another implementaion for machine learning domain is below:

for clf, title, ax in zip(models, titles, sub.flatten()):
plot_contours(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors="k")
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xlabel("Sepal length")
ax.set_ylabel("Sepal width")
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)