0

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
Pranav Patil
  • 127
  • 9
  • Use a list instead of a sequence of variables. With `[]` you actually create one. It's not an array. – Klaus D. Jan 03 '22 at 14:59

3 Answers3

1

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))
OnY
  • 897
  • 6
  • 12
1

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())}
Itay Raveh
  • 161
  • 6
1

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)

Shanavas M
  • 1,581
  • 1
  • 17
  • 24
  • Can you please explain for what purpose have you use ``` locals() ```? Actually I searched for globals and locals , but they related to global and local variables in a function . I am not able to understand the use of locals() in your solution @Shanavas M – Pranav Patil Jan 03 '22 at 17:39
  • locals() and globals() return the local/global symbol table. Creating a local/global variable will add an entry to local()/global() respectively. Most of the times it works vice versa as well. Add an entry to the locals()/globals() and you get a local/global variable. Modifying locals/globals is not recommended though. – Shanavas M Jan 04 '22 at 14:18