Each time your first loop runs, it sets linelist to a new value, overwriting any old value. After that first loop runs, linelist will contain only the split result from the last line of the file. Every time you process one line of the file, you are throwing away whatever you did with the previous line.

If you want to build a list of all words in the dictionary file, you need to make a list and append to it on each iteration of your for line in infile loop.

Also, it doesn't make much sense to use split on each line if each line is just one word, since there will be no splitting to be done.

Answer from BrenBarn on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › why is my 'for loop' not iterating over the whole list?
r/learnpython on Reddit: Why is my 'for loop' not iterating over the whole list?
October 14, 2020 -

I have a list of strings. I want to remove all items from the list that begin with the '#' character. But running my for loop only manages to remove a subset of targeted items. Then I run the loop again on the same list and it removes another set. But I have to do this several times before it gets through the whole list.

Here's my code:

for item in list:

    if item[0] == "#":
        
        list.remove(item)
	
        print("item removed: ", item)

When I run this code the first time it won't remove all the items I want it to remove. Only 9. So I copy and paste the same code into IDLE and run it again and it removes 4 more items, but still not all. So I paste and run it again and another 2 are removed, but not all. So I run it again and it removes 1, then again and it removes the last 1. This is really strange. What is happening?

Discussions

python - Why my for loop is not iterating all the values - Stack Overflow
When I run this code and give input as 25 it should return me its not a prime num, But when I debug the code the range values are not iterating into if condition, only the first value of the range is More on stackoverflow.com
🌐 stackoverflow.com
python - Why is my for loop not iterating in this code? - Stack Overflow
Simple answer: because your return statement is inside the for loop. So, probably just an indentation error. But this code is, I must say, pretty un-Pythonic. You're doing lots of iterating through ranges, which should always be a red flag: in Python you usually want to iterate through an actual thing, not ... More on stackoverflow.com
🌐 stackoverflow.com
python - Loop not iterating - Stack Overflow
I'm running into a dilemma with a for i in range(x) loop not iterating. The purpose of my program is to simulate foxes and rabbits interacting with one another on an island and printing out the More on stackoverflow.com
🌐 stackoverflow.com
Python: Why is my for loop not iterating over the entire list? - Stack Overflow
So I have an "Object Class" that looks like this (details abstracted away for readability) class Object: #this is a generic object: the player, a monster, an item, the stairs... it is always repre... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Codecademy
codecademy.com › forum_questions › 53516d00548c351007000bef
Why is this code not working ? Why does It stops looping ? | Codecademy
For a loop iteration to run it ONLY tests for the existence of a letter at the index that matches the internal loop count. If a letter exists there, it runs the code block for the loop. If not, it breaks out of the loop.
Top answer
1 of 2
2

Simple answer: because your return statement is inside the for loop. So, probably just an indentation error.

But this code is, I must say, pretty un-Pythonic. You're doing lots of iterating through ranges, which should always be a red flag: in Python you usually want to iterate through an actual thing, not a specially-constructed range. In any case, since you're not even using the loop variable (process), you should consider if a for loop is the right structure at all.

Plus, as volcano points out in the comments, most of your setup code can be shortened significantly.

2 of 2
1

You return tape in inner cycle, the one with process in range(...), so only one iteration happens. Your tape also is not long enough, you make several operations per each tape available space, I also didn't find any "termination" symbol, so it never will be long enough with such for conditions.

Here is "fixed" code:

eachconfig = [['a', ['blank', ['p1', 'r', 'r'], ['b']]], ['b', ['blank', ['p0'], ['c']]], ['c', ['blank', ['r', 'r'], ['a']]]]
def turingmachine(data):
    a = 0
    tape = []
    finalmc = data[0][0]
    for z in range(1,40):
        tape.append(' ')
    mcName = []
    m = 0
    for emc in range(1,len(data)+1):
        goal = data[m][0]
        mcName.append(goal)
        m+=1
    mcNumber = [h-1 for h in range(1,len(mcName)+1)]
    mcNameNumber = dict(zip(mcName,mcNumber))

    d = 0
    tapeposition = d
    tapescan = tape[d]
    for process in range(1,len(tape) - 8):
        b = 0
        c = 0

        cconfig = data[a][b]
        if cconfig == finalmc:
            b += 1
            scannedsymbol = data[a][b][c]
            if isinstance(scannedsymbol, str):
                if scannedsymbol.lower() in ('any', 'blank'):
                    c += 1
                    operations = data[a][b][c]
                    for cycle in operations:
                        if cycle[0] in ('p','P'):
                            tape[tapeposition] = cycle[1:]
                        elif cycle[0] in ('r', 'R'):
                            tapeposition += 1
                        elif cycle[0] in ('l', 'L'):
                            tapeposition -= 1
                        elif cycle[0] in ('e', 'E'):
                            tape[tapeposition] == ' '
                    finalmc = data[a][b][-1][0]
                    a = mcNameNumber[finalmc]
    return tape

print turingmachine(eachconfig)
🌐
CodingTechRoom
codingtechroom.com › question › -why-isnt-my-for-loop-iterating-in-python
Why Isn't My For Loop Iterating in Python? - CodingTechRoom
Solution: Define a range that has a non-zero number of elements, e.g., `range(3)`. Mistake: Incorrectly modifying the loop variable inside the loop leading to unexpected behavior. Solution: Avoid changing the loop variable within the loop's body. ...
Top answer
1 of 3
3

You set RABBITS and RABBIT_BIRTH_RATE at the beginning. Then, on every loop iteration, you set RABBITS_START to some formula involving these two numbers. You never change the value of RABBITS or RABBIT_BIRTH_RATE or FOXES or anything, so every time you run through the loop, you're just calculating the same thing again with the same numbers. You need to update the values of your variables on each iteration --- that is, set a new value for RABBITS, FOXES, etc.

2 of 3
2

The biggest issue for me is what you named your "change in rabbits/foxes". RABBITS_START sounds like an initial count for RABBITS, but it's not. This is why I renamed it to RABBITS_DELTA, because really it's calculating the CHANGE in rabbits for each day.

I think I got it. At the very least this behaves more like a simulation now:

def run_simulation():
  RABBIT_BIRTH_RATE = 0.01
  FOX_BIRTH_RATE = 0.005
  INTERACT = 0.00001
  SUCCESS = 0.01
  x = 0
  y = 1

  FOXES = eval(str(input("Enter the initial number of foxes: ")))
  RABBITS = eval(str(input("Enter the initial number of rabbits: ")))

  DAYS = eval(str(input("Enter the number of days to run the simulation: ")))

  print("Day\t","Rabbits\t","Foxes\t")
  print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")

  count = 0
  while count < DAYS:
    RABBITS_DELTA = round((RABBIT_BIRTH_RATE * RABBITS) \
                          - (INTERACT * RABBITS * FOXES))
    FOXES_DELTA = round((INTERACT * SUCCESS * RABBITS * FOXES) \
                        - (FOX_BIRTH_RATE * FOXES))
    y = y + x

    RABBITS += RABBITS_DELTA
    FOXES += FOXES_DELTA
    print (y,"\t",(RABBITS),"\t","\t",(FOXES),"\t")

    count += 1


run_simulation()
Find elsewhere
Top answer
1 of 2
6

There is both too much and not enough code there, to be able to find the "actual" problem. I would guess, though, that you are probably iterating over a list or array or collection and simultaneously removing things from it. That's a common question here on SO.

In general, you will see weird behavior like skipping over elements, or (in your case) having a list that should be empty show up as not empty.

In particular, I see you in one function doing this:

for element in monster.inventory:

In another function, you are doing this:

for object in objects:
    ...
    object.inventory.remove(self.owner)

I wonder if the monster.inventory list and the object.inventory list aren't the same at some point, which gives you a function accessing the list via an alias and removing elements, while you are trying to iterate over the list elsewhere.

Here's an example:

>>> inventory = [1,2,3]
>>> for item in inventory:
...     print(item)
...     inventory.remove(item)
...
1
3
>>> inventory
[2]

What happens is the iterator (for item in inventory) points to [1], the [1] gets .removed(), which means the iterator now points to [2], which is the new "first item" in the list. The loop finishes, the iterator advances, and now the iterator points to [3]. The [3] gets .removed(), the iterator tries to advance and reaches the end of the list, so it stops. You have now removed the [1] and the [3], and skipped over the [2].

Making a copy of the list, then iterating the copy, will ensure you iterate over every single item, while removing them from the official list.

2 of 2
2

It looks like in the first object:

Object( x=0, y=0, char='-', name='Dagger', color=libtcod.cyan, equipment=Equipment(slot='right hand', power_bonus=2) )

You don't declare the item attribute, so the following loop:

for element in monster.inventory:
    if element.item:
        element.item.drop()

the if clause interprets item as False and skips the first element.

If some exception is occurring in the initialization method of class Object (and catched) the attribute item will not exist causing the error.

🌐
Stack Overflow
stackoverflow.com › questions › 46930377 › python-for-loop-not-iterating-as-expected
Python for loop not iterating as expected - Stack Overflow
However, instead of looping through all the names in the list for each candidate, takes the name in the loop it has on that particular round and if the name does not match the candidate, writes the line and moves onto the next line (with the next name in the list).
🌐
Stack Overflow
stackoverflow.com › questions › 73651586 › for-loop-not-iterating-in-the-function-language-python
For loop not iterating in the function- Language: Python - Stack Overflow
September 8, 2022 - To make it right you've to make another list and append all the elements of ex_list into list and then return that. ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance'] def second_char(y): list = [] //creating a local list for x ...
🌐
Stack Overflow
stackoverflow.com › questions › 22599692 › for-loop-not-iterating
python 3.x - For loop not iterating? - Stack Overflow
Check your indentation. Your return statement is inside the for loop, so it would return after the first iteration.
🌐
W3Schools
w3schools.com › python › python_for_loops.asp
Python For Loops
Python Examples Python Compiler ... Q&A Python Training ... 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 the for 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. ... The for loop does not require an ...
🌐
Quora
quora.com › Why-is-my-Python-coding-not-looping
Why is my Python coding not looping? - Quora
Answer (1 of 3): It won’t loop because you have no loop operator. Throw a “for” or “while” loop block in there, and it will loop as you want it to. Here’s some documentation on how to use either one: Python for Loop Statements Python while Loop Statements
🌐
Stack Overflow
stackoverflow.com › questions › 45776998 › for-loop-not-iterating-over-file
python - for loop not iterating over file - Stack Overflow
August 20, 2017 - If you want to iterate over the file twice you can reset the location with file.seek(0). ... Thanks you very much, you hit the nail on the head. The problem is fixed. ... += IS THE ADDITION OPERATOR =+ MEANS THE VARIABLE IS EQUAL TO THE POSITIVE NUMBER SO count =+ 1 means count is equal to positive 1 while count +=1 means count plus 1 · That should solve the problem! Also, the first loop reads the whole file and you need to tell it to start from the beginning again.
🌐
Stack Overflow
stackoverflow.com › questions › 63022310 › loop-does-not-iterate-over-list
python - loop does not iterate over list - Stack Overflow
s = "okjokjokj" l = [] for i in s: l.append(i) dico = ["a", "bc", "okj"] output = [] for i in l: if i + l[l.index(i)+1] + l[l.index(i)+2] in dico: print (i+l[l.index(i)+1]+l[l.index(i)+2], "found") output.append(i + l[l.index(i)+1] + l[l.index(i)+2]) l[l.index(i)+1] = "0" l[l.index(i)+2] = "0" print(l) if i + l[l.index(i)+1] in dico: print (i+l[l.index(i)+1], "found") output.append(i + l[l.index(i)+1]) l[l.index(i)+1] = "0" print(l) if i in dico: print (i, "found") output.append(i) print(l) if i == "0": print ("nothing found") print (l) print("\n output is", output)