Search code examples
pythonturtle-graphicspython-turtle

Loop through first element of a list within a list but constrain it to only select the first item each time Python


I am attempting to loop a list within a list however, only want to select the first item of each iteration of the list. List is randomly generated each time program runs.

counter_no = rand_data #the list I'm calling
max_counter_constraint = rand_data[0][1]

while True:
  for some_move in counter_no:
      if max_counter_constraint != counter_no[some_move][0]:
         continue
      elif max_counter_constraint == counter_no[some_move[0]:
         some_loop = False

An example list would look like this: [[0,5,North] # first element is move no, second element is max move constraint, 3rd is heading (this is the only list with 3 elements). Then this would follow:[1, South],[2, South East],[3, North]...etc.]

Now in theory my code should stop the program when the move constraint == the move number. However it gives me the following error TypeError: list indices must be integers or slices, not list now I understand that I cannot call/typecast the index as python only accepts integers as indexes but I cannot seem to figure out another possible solution to this issue.

A solution I have began brainstorming is using slicing to access the list eg:

if max_counter_constraint != counter_no[0:100][0]

As the list is constrained to a maximum length of 100 individual steps would this be a viable solution that would still cancel if the max_counter_constraint == counter_no?

Also would this effect the loop?

Any advice would be helpful.


Solution

  • In for some_move in counter_no: the variable some_move is already each value of counter_no so you don't really need to index counter_no. You can simply do:

    max_counter_constraint == some_move[0]
    

    For other cases where you may need both the index and the value using an int variable that you increment on each loop would be an option, but the pythonic way is:

    for i, value in enumerate(some_list):
        ...