Home > front end >  Accessing current instance of python for loop
Accessing current instance of python for loop

Time:05-03

in Python how does one call the current position of a interation in a "for x, y, z in list():"?

I have a list with numerous subsists consisting of three variables, but I don't quite know how to call the current position of the loop - ie. Call the value of X in the current iteration of the loop.

I am really new to coding and python so any help would be appreciated greatly - I read something about enumerate but that just confused me and I didn't know whether it would help or how to reference it or use it

currently my loop looks like: for step_num, direction, changes in movements:

with movements being a list consisting of multiple sub lists with three variables each (one numeric and two alphanumeric). my goal is to be able to reference the current variable of the current sublist being iterated through - I'd read something about enumerate potentially being able to help with finding the current value of a sub list variable, however I don't know how to use it as such, if indeed it can be used like that, especially since the output is being used in a turtle window to draw different objects.

As it stands I'm not sure how to make it happen, so the functions making drawings don't know how to draw the current value in the loop

CodePudding user response:

you can use enumerate(list) like so:

for index, y in enumerate(list):
    print(index) # position of loop
    print(y) # item in list

CodePudding user response:

I'm making some assumptions here, but are you looking for something like this?

# iterate through each sublist in `movements`
# and also get its index
for ix, movement in enumerate(movements): 
    for step_num, direction, changes in movement: # extract the values from each sublist
        ... # do stuff with the index and corresponding values

P.S.: If you are new to SO, please take sometime to learn how to produce a minimal reproducible example. It will only increase your chances of getting a quick and useful response.

  • Related