![]() |
|
Using modulo to loop through lists - Printable Version +- QB64 Phoenix Edition (https://qb64phoenix.com/forum) +-- Forum: QB64 Rising (https://qb64phoenix.com/forum/forumdisplay.php?fid=1) +--- Forum: Code and Stuff (https://qb64phoenix.com/forum/forumdisplay.php?fid=3) +---- Forum: Help Me! (https://qb64phoenix.com/forum/forumdisplay.php?fid=10) +---- Thread: Using modulo to loop through lists (/showthread.php?tid=3892) |
Using modulo to loop through lists - fistfullofnails - 08-25-2025 I made the mistake of looking at some python the other day and I noticed that they were using the modulo to loop through a list. As in if there was a list of four items, the loop would contain something like Code: (Select All)
. So that being said, what's throwing me for a loop, is that I can see how that works once 'x' becomes >= than 4, but i am stumped for when x would equal 0 to 3. Would that not be 0/4, 1/4, 2/4, and 3/4? I understand that 0/4 would have a remainder of 0, but then, to me at least, 1/4 through 3/4 would not have a whole number remainder. So how would 'items[1%4]' give you the second item in the list? To me, the remainder of 1 divided by 4 is not equal to 1. It's 0.25. If I actually type out 1%4 in my prompt, it does return 1, so apparently the computer agrees with it.
RE: Using modulo to loop through lists - SMcNeill - 08-25-2025 Remember, MOD deals with integer math. 6 MOD 4 would be like saying: 6 - (INT(6 / 4) * 4)... or basically 6 - (1 * 4)... 6 - 4... 2 So if we say 1 MOD 4 it's the same basic math as 1 - (INT(1 / 4) * 4). What is 1/4? That 0.25. So do the substitution: 1 - (INT(0.25) * 4) What's the INT(0.25)? That's 0. Do that substitution. 1 - (0 * 4) Do the multiplication in the parenthesis: 1 - 0 And then do the subtraction: 1 1 MOD 4 = 1 RE: Using modulo to loop through lists - DSMan195276 - 08-25-2025 (08-25-2025, 02:15 PM)fistfullofnails Wrote: I made the mistake of looking at some python the other day and I noticed that they were using the modulo to loop through a list. As in if there was a list of four items, the loop would contain something like To add on to what Steve said, remember a remainder is always a whole number, it's what you get when you stop doing division after calculating only the whole number part of the answer and then checking what number is "left over". In the case of `1/4`, the whole number part of the answer is zero, so the "left over" part is 1. You're seeing it instead as .25 because you're continuing to do the division after you've already calculated the whole number part of the answer. RE: Using modulo to loop through lists - fistfullofnails - 09-03-2025 Thank both of you for your help |