0

If we want to call some function by passing arguments that are variables named in some sequence x1, x2, x3,....

def helloWorld(a):
   some code

how to loop and pass them . instead of writing function call for each

helloWorld(x1)
helloWorld(x2)
helloWorld(x3)
....

maybe something like

for i in range(100):
   helloWorld(xi)
pranav nerurkar
  • 596
  • 7
  • 19

3 Answers3

4

Just put the values in a list and iterate over it:

for x in [x1, x2, x3]:
    helloWorld(x)
Thomas
  • 174,939
  • 50
  • 355
  • 478
1

Instead of naming the variables x1, x2, x3, ..., consider using a dictionary or, better, a list, to store these values. Then call the method like so (in this example, using a list):

lst = ['foo', 'bar', 'baz']
for x in lst:
    helloWorld(x)
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
0

try this: (be careful when using eval)

for i in range(100):
   helloWorld(eval("x" + str(i)))
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • 6
    Just note that `eval` is evil and should only be used as a last resort. There are almost always better approaches. – Thomas Sep 09 '21 at 14:06
  • Many argue against using `eval` where possible, for example: https://stackoverflow.com/q/1832940/967621 . In the case of the OP, it is possible to avoid `eval` by refactoring the code and using better structures to store values (e.g., list or dict instead of individual variables). – Timur Shtatland Sep 09 '21 at 15:09