Jump to content

Python ForLoop indexing

I need to make a loop in python that is checking a list of numbers at as such:

for x in range(y):
  if a == x+1:
	n += 1

So that the variable y will naturally iterate past its index range. So I need to know how I can accomplish this without being stopped by the index out of range error.

Link to comment
Share on other sites

Link to post
Share on other sites

If I understand the question correctly you want to change the range from within the for loop?

In Python you need to use a while loop to do something like that:

x = 0
while (x < y):
    if ...:
        y += 1
    x += 1

 

Desktop: Intel i9-10850K (R9 3900X died 😢 )| MSI Z490 Tomahawk | RTX 2080 (borrowed from work) - MSI GTX 1080 | 64GB 3600MHz CL16 memory | Corsair H100i (NF-F12 fans) | Samsung 970 EVO 512GB | Intel 665p 2TB | Samsung 830 256GB| 3TB HDD | Corsair 450D | Corsair RM550x | MG279Q

Laptop: Surface Pro 7 (i5, 16GB RAM, 256GB SSD)

Console: PlayStation 4 Pro

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, mathijs727 said:

If I understand the question correctly you want to change the range from within the for loop?

In Python you need to use a while loop to do something like that:


x = 0
while (x < y):
	if ...:
    	y += 1
    x += 1

 

While that is a good solution, I probably should've mentioned that the for loop is also doing many other things on every iteration, including extracting one line of a file each time into a variable. So I need  a solution that allows me to keep the for loop, but iterate perhaps in a way that doesn't cause an error.

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, Lunar Evolution said:

While that is a good solution, I probably should've mentioned that the for loop is also doing many other things on every iteration, including extracting one line of a file each time into a variable. So I need  a solution that allows me to keep the for loop, but iterate perhaps in a way that doesn't cause an error.

That is what i am suggesting.

You can extend my while loop example with whatever code you want:

x = 0
while (x < y):
    INSERT CODE HERE
    if ...:
        y += 1
    OR HERE MAYBE?
    x += 1

 

Desktop: Intel i9-10850K (R9 3900X died 😢 )| MSI Z490 Tomahawk | RTX 2080 (borrowed from work) - MSI GTX 1080 | 64GB 3600MHz CL16 memory | Corsair H100i (NF-F12 fans) | Samsung 970 EVO 512GB | Intel 665p 2TB | Samsung 830 256GB| 3TB HDD | Corsair 450D | Corsair RM550x | MG279Q

Laptop: Surface Pro 7 (i5, 16GB RAM, 256GB SSD)

Console: PlayStation 4 Pro

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×