You can use dictionary. This approach is better in my opinion as you can see the the key and value pair.

code

total_squares=8
box_list={}
for q in range(total_squares):
    box_list['box_'+str(q)]=0

print(box_list)

output

{'box_0': 0, 'box_1': 0, 'box_2': 0, 'box_3': 0, 'box_4': 0, 'box_5': 0, 'box_6': 0, 'box_7': 0}
Answer from user9221519 on Stack Overflow
Discussions

Is using variables (i,j,k) in "for loop" a good practice or should i start naming them?
i is a good choice, its common knowledge that i is meant as index j is also a good choice, its the next one after i and also common knowledge as soon as you start with k, you should probably consider to make some functions and not have 3 nested loops inside a single function More on reddit.com
🌐 r/cpp_questions
21
11
April 25, 2021
language agnostic - What is an ideal variable naming convention for loop variables? - Stack Overflow
I always use a meaningful name unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use i. ... text searches for the variable name to return relevant pieces of code operating on the same data are more reliable. More on stackoverflow.com
🌐 stackoverflow.com
Why does everyone teach FOR LOOPS with the same variable name?
What variable name would you use? More on reddit.com
🌐 r/learnpython
62
33
February 12, 2022
Looping over variables names properly
I have a few arrays, say x, y, z, and I want to take all of their means and put them into new variables as x_mean = mean(x). Is there a way to do this in a for loop? Something like for a in ["x", "y", "z"] $a_mean = mean($a) end More on discourse.julialang.org
🌐 discourse.julialang.org
1
0
May 4, 2022
🌐
Runestone Academy
runestone.academy › ns › books › published › foppff › more-about-iteration_naming-variables-in-for-loops.html
7.7 Naming Variables in For Loops
Use singular nouns for the iterator variable, which is also called the loop variable (things like “song”, “book”, “post”, “letter”, “word”). ... Use plural nouns for the sequence variable (things like “songs”, “books”, “posts”, “letters”, “words”). ... ...
🌐
JMP User Community
community.jmp.com › t5 › Discussions › Setting-a-variable-name-within-a-for-loop › td-p › 54133
Solved: Setting a variable name within a for loop - JMP User Community
March 30, 2018 - Solved: Hi, I like to set variable names such as name1, name2,... in a for loop with the following arrangement: name1 = ntable; name2
🌐
Reddit
reddit.com › r/cpp_questions › is using variables (i,j,k) in "for loop" a good practice or should i start naming them?
Is using variables (i,j,k) in "for loop" a good practice or should i start naming them? : r/cpp_questions
April 25, 2021 - If you are talking about the normal for (int i = 0; i < n; ++i) loops then I'd keep them, everyone immediately recognizes those letters as loop variables. However in most cases (whenever you don't actually need the indices) then you should prefer a range based loop (for (const auto& a : iterable)) and depending on what you are doing I'd name the loop variables accordingly, e.g.
🌐
Runestone Academy
runestone.academy › ns › books › published › fopp › Iteration › WPNamingVariablesinForLoops.html
7.10. 👩‍💻 Naming Variables in For Loops — Foundations of Python Programming
Use singular nouns for the iterator variable, which is also called the loop variable (things like “song”, “book”, “post”, “letter”, “word”). Use plural nouns for the sequence variable (things like “songs”, “books”, “posts”, “letters”, “words”). While these ...
🌐
Python Forum
python-forum.io › thread-23500.html
Changing a variable's name on each iteration of a loop
Is it possible in python to change the name of a variable on each iteration of a loop? For example: for i in range(10): variableNameToChange+i='iterationNumber=='+str(i)I know this won't work, and you can't assign to an operator, but how would y...
Find elsewhere
Top answer
1 of 16
48

I always use a meaningful name unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use i.

When using meaningful names:

  • the code is more understandable to colleagues reading your code,
  • it's easier to find bugs in the loop logic, and
  • text searches for the variable name to return relevant pieces of code operating on the same data are more reliable.

Example - spot the bug

It can be tricky to find the bug in this nested loop using single letters:

int values[MAX_ROWS][MAX_COLS];

int sum_of_all_values()
{
    int i, j, total;

    total = 0;
    for (i = 0; i < MAX_COLS; i++)
        for (j = 0; j < MAX_ROWS; j++)
             total += values[i][j];
    return total;
}

whereas it is easier when using meaningful names:

int values[MAX_ROWS][MAX_COLS];

int sum_of_all_values()
{
    int row_num, col_num, total;

    total = 0;
    for (row_num = 0; row_num < MAX_COLS; row_num++)
        for (col_num = 0; col_num < MAX_ROWS; col_num++)
             total += values[row_num][col_num];
    return total;
}

Why row_num? - rejected alternatives

In response to some other answers and comments, these are some alternative suggestions to using row_num and col_num and why I choose not to use them:

  • r and c: This is slightly better than i and j. I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with "r", and readability would suffer even if other objects beginning with "r" appeared anywhere in the code.
  • rr and cc: This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better than r and c.
  • row and col: At first glance this seems more succinct than row_num and col_num, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. If row could mean either the row structure itself, or a row number, then confusion will result.
  • iRow and iCol: This conveys extra information, since i can mean it's a loop counter while Row and Col tell you what it's counting. However, I prefer to be able to read the code almost in English:
    • row_num < MAX_COLS reads as "the row number is less than the maximum (number of) columns";
    • iRow < MAX_COLS at best reads as "the integer loop counter for the row is less than the maximum (number of) columns".
    • It may be a personal thing but I prefer the first reading.

An alternative to row_num I would accept is row_idx: the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar.

My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs.

In summary, my aim with all variable naming (not just loops) is to be completely unambiguous. If anybody reads any portion of my code and can't work out what a variable is for immediately, then I have failed.

2 of 16
37

1) For normal old style small loops - i, j, k - If you need more than 3 level nested loops, this means that either the algorithm is very specific and complex, or you should consider refactoring the code.

Java Example:

for(int i = 0; i < ElementsList.size(); i++) {
  Element element = ElementsList.get(i);
  someProcessing(element);
  ....
}

2) For the new style java loops like for(Element element: ElementsList) it is better to use normal meanigful name

Java Example:

for(Element element: ElementsList) {
  someProcessing(element);
  ....
}

3) If it is possible with the language you use, convert the loop to use iterator

Java Iterator Example: click here

🌐
Reddit
reddit.com › r/learnpython › why does everyone teach for loops with the same variable name?
r/learnpython on Reddit: Why does everyone teach FOR LOOPS with the same variable name?
February 12, 2022 -

I'm trying to learn for loops but it feels like everyone teaches examples writing for loops with the same variable name but in the singular form.

Example:

For number in numbers:

For course in courses:

For plane in planes:

For car in cars:

Is there a reason why most people like writing their for loops this way. For me it takes a while to understand more than if they used a different variable name entirely.

🌐
Quora
quora.com › When-writing-a-for-loop-why-does-everyone-name-the-variable-as-i
When writing a 'for' loop, why does everyone name the variable as 'i'? - Quora
Answer (1 of 35): i and j have typically been used as subscripts in math for quite some time (e.g., even in papers that obviously predate computers, you frequently see things like "Xi,j", especially in things like a summation). Fortran (programming language), which influenced many families of la...
🌐
JMP User Community
community.jmp.com › t5 › Discussions › How-to-create-variable-names-depending-on-loop-number › td-p › 7422
Solved: How to create variable names depending on loop number - JMP User Community
January 3, 2019 - I would eventually like to have var1, var2, var3, etc... till the loop is done ... Created: Sep 17, 2013 06:53 PM | Last Modified: Jan 2, 2019 1:08 PM (21403 views) | Posted in reply to message from abdulj 09-17-2013 ... // dv = dummy variable x = 10; For( i = 1, i <= x, i++, Eval( Substitute( Expr( dv_variable = i; Show( dv_variable ); ), Expr( dv_variable ), Parse( "Variable Name " || Char( i ) ) ) ) );
🌐
Posit Community
forum.posit.co › general
Using variables names in loops - General - Posit Community
February 8, 2022 - I wish to run through variables ... for (i in 1:2) { variable = paste0("a", i) mean = mean(as.name(variable)) print(as.name(mean)) } This actually doesn't work, since it is not taking the variable values but the variable as a name. On top of that I wish to create numerous mean variables using the number in the loop ...
🌐
Arduino Forum
forum.arduino.cc › projects › programming
[RESOLVED] variable name with a for loop , Is it possible ? see example - Programming - Arduino Forum
March 14, 2018 - Hi i would like to know if this is possible to change variable name with a for loop , and if not have an explanation. If it is possible could you please learn me the way. See the examples above for what i want to know: THIS CODE byte i; byte Example1[5] = {1, 2, 3, 4, 5} ; byte Example2[5] = {11, 12, 13, 14, 15} ; byte Example3[5] = {31, 32, 33, 34, 35} ; void setup() { Serial.begin(115200); Serial.println("HELLO"); Serial.println(""); } void loop() { for (i = 0; i
🌐
Statistics Globe
statisticsglobe.com › home › learn r programming (tutorial & examples) | free introduction › name variables in for-loop dynamically in r (2 examples)
Name Variables in for-Loop Dynamically in R (2 Examples) | Assign Names
March 17, 2022 - This variable should be named variable_1. Then, we can apply the assign function as shown below: assign("variable_1", my_list[[1]]) # Apply assign function variable_1 # 1 2 3 4 5 · An advantage of the assign function is that we can create new variables based on a character string. You’ll see this advantage in the next example in action! The following R codes is again using the assign function, but this time within a for-loop.
🌐
OARC Stats
stats.oarc.ucla.edu › r › codefragments › looping_strings
How can I loop through a list of strings as variables in a model? | R Code Fragments
A single string is generated using paste that contains the code for the model, and then we use eval and parse to evaluate this string as code. hsb2 <- read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv") names(hsb2) ## [1] "id" "female" "race" "ses" "schtyp" "prog" "read" ## [8] "write" "math" "science" "socst" varlist <- names(hsb2)[8:11] models <- lapply(varlist, function(x) { lm(substitute(read ~ i, list(i = as.name(x))), data = hsb2) }) ## look at the first element of the list, model 1 models[[1]]
🌐
GeeksforGeeks
geeksforgeeks.org › python › changing-variable-names-with-python-for-loops
Changing Variable Names With Python For Loops - GeeksforGeeks
July 23, 2025 - In this example, below Python code below adds the prefix "var_" to each variable name in the list original_names. It uses a for loop to iterate through the original names, creates new names with the prefix, and appends them to the list prefixed_names.