Python For loop Iteran - python

How can I change value of a variable which iterating over?
for i in range(10,30):
print('jdvcjhc')
I want to change I value like i do in while loop
i=1`enter code here`
while i<=10
print('dfhs')

You can't set conditional statements like (i<=10) in For loops. you just can set the range that "i" can change. Actually, if you need a condition for your loop you need to use While or For and If together.
That's my opinion.
Regards,
Shend
Edit: if you need to change the steps of adding or subtracting "i" you can use step in range function. ( range(start,stop,step)).

The range function returns a pre-calculated list of values, created from the input parameters, in this case - (10, 30). Unlike while loop, i here is a 'dummy' variable used as a placeholder for the values read from the list. Within a particular iteration, one can manipulate i as much as they like, but it will inevitably become overwritten with the subsequent list value upon calling the next iteration.

Related

Accessing current instance of python for loop

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
you can use enumerate(list) like so:
for index, y in enumerate(list):
print(index) # position of loop
print(y) # item in list
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.

How to turn error message into a bool value?

i=5
while bool(controller[i]):
controller_jsn['Transition']=controller[i]
i+=1
I write a code above. And try to stop the loop when i is out of range. bool() is not the way. what methode should I use?
The more common way to write this code would be to iterate over the elements directly, instead of using indices. Use a slice if you need to start at the 5th element instead of looping over all elements.
for c in controller[5:]:
controller_jsn['Transition'] = c
but I hope you have more logic in there, because each iteration of the loop just overwrites the same value.

Swapping elements in a list without using a temporary variable

def swap_firstandlast(list):
list[-1],list[0] = list[0],list[-1]
print(list)
When asked to swap two values I always use a temporary variable to a value and then assign it a new value until I saw this code. Can someone explain this code? Like in what order the values gets assigned. Like if list[-1] first gets assigned the value of list[0] then the output will be wrong right but this code works perfectly fine and I want to know how it works.
The code works because you are not modifying the two elements with two separate statements.
You have basically extracted them as a tuple and assigned them the values ​​currently in memory, and the values ​​in memory are not changed until the entire instruction is processed correctly.

Do elements of a list inside a dictionary change it's order in Python?

I have a list inside a dictionary, it seems to change it's order in every iteration.
Consider this example,
a={ID: [value, [1,2,3,4,5,6]]}
When I access a[ID][1], will it give [1,2,3,4,5,6] (in order) everytime I access this?
Yes, a[ID][1] should give the same list in order each time. Unless you change a somewhere else within your program.

Python: Easy way to loop through dictionary parameters from a list of evaluated strings?

I have a dictionary created from a json file. This dictionary has a nested structure and every few weeks additional parameters are added.
I use a script to generate additional copies of the existing parameters when I want multiple "legs" added. So I first add the additional legs. So say I start with 1 leg as my template and I want 10 legs, I will just clone that leg 9 more times and add it to the list.
Then I loop through each of the parameters (called attributes) and have to clone certain elements for each leg that was added so that it has a 1:1 match. I don't care about the content so cloning the first leg value is fine.
So I do the following:
while len(data['attributes']['groupA']['params']['weights']) < legCount:
data['attributes']['groupA']['params']['weights'].append(data['attributes']['groupA']['params']['weights'][0])
while len(data['attributes']['groupB']['paramsGroup']['factors']) < legCount:
data['attributes']['groupB']['paramsGroup']['factors'].append(data['attributes']['groupB']['paramsGroup']['factors'][0])
while len(data['attributes']['groupC']['items']['delta']) < legCount:
data['attributes']['groupC']['items']['delta'].append(data['attributes']['groupC']['items']['delta'][0])
What I'd like to do is make these attributes all strings and just loop through them dynamically so that when I need to add additional ones, I can just paste one string into my list and it works without having another while loop.
So I converted it to this:
attribs = [
"data['attributes']['groupA']['params']['weights']",
"data['attributes']['groupB']['paramsGroup']['factors']",
"data['attributes']['groupC']['items']['delta']",
"data['attributes']['groupD']['xxxx']['yyyy']"
]
for attrib in attribs:
while len(eval(attrib)) < legCount:
eval(attrib).append(eval(attrib)[0])
In this case eval is safe because there is no user input, just a defined list of entries. Tho I wouldn't mind finding an alternative to eval either.
It works up until the last line. I don't think the .append is working on the eval() result. It's not throwing an error.. just not appending to the element.
Any ideas on the best way to handle this?
Not 100% sure this will fix it, but I do notice one thing.
In your above code in your while condition you are accessing:
data['attributes']['groupA']['params']['weights']
then you are appending to
data['attributes']['groupA']['params']['legs']
In your below code it looks like you are appending to 'weights' on the first iteration. However, this doesn't explain the other attributes you are evaluating... just one red flag I noticed.
Actually my code was working. I was just checking the wrong variable. Thanks Me! :)

Categories