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 OverflowYou 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}
Creating variables dynamically is an anti-pattern and should be avoided. What you need is actually a list:
total_squares = 8
box_list = []
boxes = [0] * total_squares
for q in range(total_squares):
box_list.append(boxes[q])
Then you can refer to any element you want (say, box_i) using the following syntax:
my_box = box_list[boxes[i]]
i,j and k are the standard counter variables. By using them you imply the variables are used to keep loop count and nothing else. If you use another more complex name then its less clear what the variable is used for.
If your counter variables are getting confusing then its a sign your code needs breaking up. i.e
for(int i=0;i<numMesh;i++)
foo += CountVerticies(meshes[i]);
for standard looping people pick i,j,k because it is easy and in a lot of situations you don't have a meaning for it so i,j,k is meaningful also known by all developer so it is pretty close to a standard.
anyway if you need to change to something more meaningful, use the following guidelines that i picked from uncle bob book "Clean Code" note there is other things also to consider from the book, but this is what i thought fit to the looping name: -
- Use Intention-Revealing Names
- Avoid Disinformation
- Make Meaningful Distinctions
- Use Pronounceable Names
- Use Searchable Names
- Avoid Encodings (Hungarian Notation,Member Prefixes)
- Don't be cute
- Pick One Word per Concept
so the code will end up something like this more or less
for(int cellPointer = 0; cellPointer < 10;cellPointer++)
{
for (int rowPointer = 0; rowPointer < 10; rowPointer++)
{
//do something
}
}
so when you go back to it you can understand it, if somebody from outside got to work on it after you i'll be readable to him
Is using variables (i,j,k) in "for loop" a good practice or should i start naming them?
language agnostic - What is an ideal variable naming convention for loop variables? - Stack Overflow
Why does everyone teach FOR LOOPS with the same variable name?
Looping over variables names properly
Videos
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:
randc: This is slightly better thaniandj. 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.rrandcc: 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 thanrandc.rowandcol: At first glance this seems more succinct thanrow_numandcol_num, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. Ifrowcould mean either the row structure itself, or a row number, then confusion will result.iRowandiCol: This conveys extra information, sinceican mean it's a loop counter whileRowandColtell you what it's counting. However, I prefer to be able to read the code almost in English:row_num < MAX_COLSreads as "the row number is less than the maximum (number of) columns";iRow < MAX_COLSat 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.
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
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.
Sure you can; it's called a dictionary:
d = {}
for x in range(1, 10):
d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}
I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!
It is really bad idea, but...
for x in range(0, 9):
globals()['string%s' % x] = 'Hello'
and then for example:
print(string3)
will give you:
Hello
However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.