How To Declare A Lot of Empty List Using For Loops and Array?

 


Sometimes in the project, we need to declare a lot of variables and an empty list like this, and as the project grows, you are required to declare a lot of variables, which will cost your space and make your code messy. So imagine when you have hundreds of empty lists later on and you need to declare like this for hundreds of lines. Not just show you like an idiot, but make other's life harder




Therefore, here I come to be your saviour, to help you guys write clean code to save you from this disaster. So you can do this by using nested for loop of arrays. But before that let's understand what is Array and For Loops first.


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like for the keyword in other programming languages and works more like an iterator method as found in other object-orientated programming languages. With the for loop, we can execute a set of statements, once for each item in a list, tuple, set etc.


Arrays are used to store multiple values in one single variable:


So how to apply all of this to our problems?


lst1 = ["from","insert","create"]

lst2 = ["_table","_list"]


for iter1 in lst1:

  for iter2 in lst2:

     print(iter1 + iter2)


then the output will be like :


This still not solving our problem because what we produce now is just a string, not a variable, even an empty list. so modify a bit your code like this which is adding locals at the front, and now you are good to go.

The locals() function in python is used to return the dictionary of the current local symbol table. The local symbol table is accessed with the help of the locals() function. This function works the same as the globals() function. The only difference between them is the locals() function access the local symbol table, and the globals() access the global symbol table, and both return the dictionary.


lst1 = ["from","insert","create"]

lst2 = ["_table","_list"]

for iter1 in lst1:

  for iter2 in lst2:

     locals()[iter1 + iter2] = []


then all of the variables are been declared automatically and stored inside the cached. so next time if you want to add or declare a new empty list, just add more rows inside the array whether the first array or the second array.

Thank you.


"You were my greatest blessing but not my answered prayer,
Maybe I'm just your once upon a time not your happy ever after."



Post a Comment

0 Comments