Home > Software engineering >  Python how to declare dynamic ( number of arrays )
Python how to declare dynamic ( number of arrays )

Time:01-04

I want to take integer as input and declare that many arrays with array_names as starting form 0 to that integer for example :

if I give input as 3 , then in my code there should be 
arr1 = [] ,
arr2 = [] ,
arr3 = []

I tried this but its giving syntax error

arr = []
no_of_arrays = int(input())
for i in range(no_of_arrays):
       arr{i} = [] 

its giving

SyntaxError: invalid syntax

CodePudding user response:

There is no good way to declare primitive variables dynamically.
You can either create a dictionary d={'Array1':[]....} or try looking into exec function - which is not recommended for many reasons:

for i in range(int(input())):
    exec('myArr{}=[]'.format(i))

CodePudding user response:

You can create a variable by updating the globals or locals dict.

eg:

l = locals()
no_of_arrays = int(input())
for i in range(no_of_arrays):
  l[f"arr{i}"] = []

print(arr0)
print(arr1)

CodePudding user response:

While you can technically do this in python using exec, it is not recommended.

Instead, you should create a list of lists:

arrays = [[] for _ in range(int(input())]

Or a dictionary of lists:

arrays = {f'arr{i}': [] for i in range(int(input())}
  • Related