For Loop in Python

for loop in Python

You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.

mylist = [1,2,3]
for item in mylist:
print item

mydict = {1:'one', 2:'two', 3:'three'}
for key in mydict:
print key, mydict[key]

This is actually faster than using the above code with range(), and removes the extraneous i variable.

If you need to edit items of a list in-place, then you do need the index, but there's still a better way:

for i, item in enumerate(mylist):
mylist[i] = item**2

Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.

Understanding for loops in Python

A for loop takes each item in an iterable and assigns that value to a variable like w or number, each time through the loop. The code inside the loop is repeated with each of those values being re-assigned to that variable, until the loop runs out of items.

Note that the name used doesn't affect what values are assigned each time through the loop. Code like for letter in myvar: doesn't force the program to choose letters. The name letter just gets the next item from myvar each time through the loop. What the "next item" is, depends entirely on what myvar is.

As a metaphor, imagine that you have a shopping cart full of items, and the cashier is looping through them one at a time:

for eachitem in mybasket: 
# add item to total
# go to next item.

If mybasket were actually a bag of apples, then eachitem that is in mybasket would be an individual apple; but if mybasket is actually a shopping cart, then the entire bag could itself meaningfully be a single "item".

How to make a for-loop more understandable in python?

You could show them this code for a better understanding:

start = 1
length = 10
for i in range(start,start+length):
print(i)

There is also another feature that works like this, it's called slice.

How to return the list name in for loop in Python

If you make the lists dictionaries you can provide a name

list1 = { "name": list1, "list": [1,2,3]}
list2 = { "name": list2, "list": [4,5,6]}

list_all = [list1,list2]

for i in list_all:
print(list_all[i].name)

Multiprocessing a for loop in Python

I suppose the quickest / simplest way to get there is to use a multiprocessing pool and let it run across iterable (of your files)... A minimal example with fixed number of workers and a little extra info to observe behavior would be:

import datetime
import time

from multiprocessing import Pool

def long_running_task(filename):
time.sleep(1)
print(f"{datetime.datetime.now()} finished: {filename}")

filenames = range(15)

with Pool(10) as mp_pool:
mp_pool.map(long_running_task, filenames)

This creates a pool of 10 workers and will call long_running_task with each item from filenames (here just series of 0..14 ints as a stand-in) as a task finishes and the worker becomes available.

Alternatively, if you wanted to iterate over the inputs yourself, you could do something like:

with Pool(10) as mp_pool:
for fn in range(15):
mp_pool.apply_async(long_running_task, (fn,))
mp_pool.close()
mp_pool.join()

This would pass fn as first positional argument for each long_running_task call... when assigning all the work, we need to close the pool to stop accepting any more requests and join to wait for any outstanding jobs to finish.

Storing values in a for loop in Python

@Ali_Sh's comment is correct, and the usage here is simply b = a + 1, and that's that.

I will assume you are dumbing down some complicated use case which requires looping, so here is your code in a working form:

import numpy as np

a = np.array([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],

[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]])

ar = []
for x in range(0,2):
b = a[x, :] + 1
ar.append(b)

print(np.stack(ar))

For loop in c# vs For loop in python

What you're likely running into here is integer overflow with the C# version of the Factorial function (at least your implementation of it, or wherever its coming from).

In C#, an int is a numerical type stored in 32 bits of memory, which means it's bounded by -2^31 <= n <= 2^31 - 1 which is around +/- 2.1 billion. You could try using a long type, which is a 64 bit numerical type, however for even larger upper bounds in your for loop, like getting close to 100, you're going to overflow long as well.

When you run the Factorial function in C#, it starts off normally for the first little while, however if you keep going, you'll see that it all of a sudden jumps into negative numbers, and if you keep going even further than that, it'll get to 0 and stop changing. You're seeing the output of infinity due to division by 0, and C# has a way of handling that with doubles; that being to just return double.PositiveInfinity.

The reason why this doesn't happen in python is that it uses a variable number of bits to store its numerical values.

Added note: What you might also want to try is using a Factorial function that works with the double type instead of int or long, however by doing this, you'll lose precision on what the exact value is, but you get more range as the magnitude of the number you can store is larger

Further Note: As mentioned in the comments, C# has a type called BigInteger which is designed to handle huge numbers like the values you would expect from large inputs to a Factorial function. You can find a reference to the BigInteger docs here


What you can do is calculate each component of the factorial function separately with the power you're using. Here's what I mean:

public decimal Exp(decimal power, int accuracy = 100)
{
decimal runningTotal = 1;
decimal finalValue = 1;
for (int i = 1; i <= accuracy; i++)
{
runningTotal *= power/i;
finalValue += runningTotal;
}
return finalValue;
}


Related Topics



Leave a reply



Submit